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
template.ehtmlimport { 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 makes a square box and 9 / 16 a portrait one.
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
fit="contain" shows the entire 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 fixed. The height follows the ratio.
Code
<AspectRatio ratio={ratioOf(state.choice)} class="rounded">...</AspectRatio>Space held before loading
An image that has not loaded still takes its box. The caption under it 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
Any child fills the box, including content that is not media.
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>