Displays content within a desired ratio, and glides to a new one when it changes.
Installation#
bunx --bun fabricator-ui@latest add aspect-ratio
Usage#
import { AspectRatio } from "@/components/ui/aspect-ratio"<AspectRatio ratio={16 / 9} className="overflow-hidden rounded-xl bg-muted">
<Image src="..." alt="..." fill className="object-cover" />
</AspectRatio>The frame takes its width from its parent or className, and its height from ratio. Give it overflow-hidden and a radius to clip what's inside, and bg-muted so it holds its shape while an image loads.
Changing the ratio#
When ratio changes, the frame glides to the new shape on the move timing (duration-move ease-move, 250ms at the default speed). Under reduced motion it snaps. The demo at the top switches between five ratios; its frame keeps the same area, so the photo reshapes around its centre.
Examples#
Square#
ratio={1 / 1}, for avatars, album art and product tiles.
Portrait#
ratio={9 / 16}, for stories, reels and phone screenshots.
API Reference#
AspectRatio#
The AspectRatio component displays content within a desired ratio.
| Prop | Type | Default | Required |
|---|---|---|---|
ratio | number | - | Yes |
className | string | - | No |
It also takes every div prop. A style prop merges with the ratio.
Accessibility#
- The frame is a plain
divwith no role, so screen readers read only what's inside it. - Give every image inside it an
altthat says what it shows, oralt=""when it's decoration. Aniframetakes atitle. - A ratio switcher, as in the demo, is a
ToggleGroupwith anaria-label; each item's text names its ratio.