Aspect Ratio
Holds a box at a fixed width to height ratio so media does not shift the layout.
Installation
pnpm dlx shadcn@latest add @silkware/aspect-ratioTo copy the component by hand, install its dependency:
pnpm add cnThen copy the source into components/ui/aspect-ratio.tsx:
import { cn } from "cn"
function AspectRatio({ ratio, className, ...props}: React.ComponentProps<"div"> & { ratio: number }) { return ( <div data-slot="aspect-ratio" style={ { "--ratio": ratio, } as React.CSSProperties } className={cn("relative aspect-(--ratio)", className)} {...props} /> )}
export { AspectRatio }Usage
import { AspectRatio } from "@/components/ui/aspect-ratio"<AspectRatio ratio={16 / 9}> <img src="/sites/bergamo.jpg" alt="The Bergamo site" className="size-full object-cover" /></AspectRatio>ratio is width divided by height and is required. The box takes the width of its container. Make the content fill it with size-full and, for images, object-cover.
Examples
Landscape
16 / 9 suits photos of sites and wide previews.
Square
1 suits product photos and avatars of equal sides.
Portrait
3 / 4 suits documents and tall photos. Limit the width of the wrapper so the box does not become taller than the screen.
Accessibility
AspectRatio renders a plain div and adds no semantics and no keyboard interaction.
You provide:
- A text alternative for the media inside: the
altattribute of an image, or a caption for a video. - Content that fits the box. Text that is taller than the box makes it grow and the ratio is lost.
Guidelines
When to use
- Around images, video and maps whose size is known only at run time, to reserve the space before they load.
- To keep a grid of thumbnails the same shape.
When not to use
- For text, forms or other content that sets its own height. Use normal layout.
- For a fixed pixel size. Set
widthandheighton the element.
Content
- Pick one ratio for a set of items, and keep it.
- Crop with
object-cover. Useobject-containwhen cropping would hide something that matters, such as a label on a part.
Fill the box with media or a placeholder of the same shape.
Don’t put text that is taller than the box. The box stretches and stops holding its ratio.
API reference
AspectRatio
Renders a div with aspect-ratio set from a CSS variable. It accepts every div prop.
| Prop | Type | Default | Description |
|---|---|---|---|
ratio | number | None | Width divided by height, for example 16 / 9. |
className? | string | None | Classes merged after the base classes. |