AspectRatio
Keeps media at a fixed width-to-height ratio, with its space held before it loads.
16:9
An image held at 16 by 9 at any width.
Code
<AspectRatio ratio={16 / 9} class="rounded">
<img src="./photo.jpg" alt="Mountains at sunset">
</AspectRatio>Usage
import { AspectRatio } from "@elements/ui/aspect-ratio";
<AspectRatio ratio={16 / 9}>
<img src="./hero.jpg" alt="A mountain lake at dawn">
</AspectRatio>Examples
Square and portrait
ratio 1 and 9 / 16.
Code
<AspectRatio ratio={1 / 1} class="rounded"><img src="./photo.jpg" alt="..."></AspectRatio>
<AspectRatio ratio={9 / 16} class="rounded"><img src="./photo.jpg" alt="..."></AspectRatio>Fit
contain shows the whole image inside the box.
Code
<AspectRatio ratio={16 / 9} fit="contain" class="rounded">
<img src="./photo.jpg" alt="...">
</AspectRatio>Change the ratio
The width stays; the height follows the ratio.
Code
<AspectRatio ratio={ratioOf(state.choice)} class="rounded">...</AspectRatio>Space held before loading
An image that has not arrived still takes its box, so the caption never moves.
This line never moves when the image arrives.
Code
<AspectRatio ratio={16 / 9} class="rounded">
<img src="/slow.jpg" alt="...">
</AspectRatio>
<p>This line never moves when the image arrives.</p>Any content
Not only media: each child fills the box.
Map
ratio 0 falls back to 1
Code
<AspectRatio ratio={4 / 3} class="rounded">
<div class="map">Map</div>
</AspectRatio>RTL
The box keeps its ratio whatever the direction.
Code
<div dir="rtl">
<AspectRatio ratio={16 / 9}><img src="./photo.svg" alt="جبال عند الغروب"></AspectRatio>
</div>