Aspect Ratio
An Aspect Ratio keeps a box at a set ratio of width to height so that users see its content in the same shape at any width.
When to Use
- for an image that keeps one shape as its column narrows, such as a cover at 16 to 9
- to reserve the space of an image before it loads, so that the content under it doesn’t move when the image arrives
When Not to Use
- for a person’s image (use an Avatar, which has a fixed size)
- to page through images of one shape (use a Carousel)
- to show a placeholder while an image loads (use a Skeleton)
Accessibility
An Aspect Ratio is a div with no role, and it can’t receive focus. The meaning is in its content, so an image inside it needs an alt for screen readers to announce, as WCAG 2.2 SC 1.1.1 Non-text Content requires.
Installation
npx shadcn@latest add @summit/aspect-ratioUsage
ratio is the width divided by the height. The box is as wide as its container, or as wide as a width class sets it, and its height follows from the ratio.
import { AspectRatio } from '@/components/ui/aspect-ratio';
<AspectRatio ratio={16 / 9} className="w-96 overflow-hidden rounded-lg bg-muted">
<img src="/cover.jpg" alt="Hills at sunset" className="size-full object-cover" />
</AspectRatio>;Fill the Box
To make an image fill the box, add size-full object-cover to the image. The image then covers the box and is cropped to the ratio. The box is relative, so a child with absolute inset-0 covers it too.
size-full object-cover to the image so that it fills the box and is cropped to the ratio.Tall Content
If the content is taller than the ratio allows, the box grows. To keep the ratio and clip the content, add overflow-hidden.
<AspectRatio ratio={16 / 9} className="overflow-hidden">
<p>A long caption</p>
</AspectRatio>API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
ratio | number | Required | The width divided by the height: 16 / 9, 4 / 3, or 1 for a square |
Other props are passed to the div. AspectRatio writes ratio to the --ratio variable in an inline style, which is merged with any style you pass.