Skip to content

Aspect Ratio

Holds a box at a fixed width to height ratio so media does not shift the layout.

Photo of the Bergamo site

Installation

pnpm dlx shadcn@latest add @silkware/aspect-ratio

To copy the component by hand, install its dependency:

pnpm add cn

Then copy the source into components/ui/aspect-ratio.tsx:

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.

Photo of the Bergamo site

Square

1 suits product photos and avatars of equal sides.

Photo of the steel bracket

Portrait

3 / 4 suits documents and tall photos. Limit the width of the wrapper so the box does not become taller than the screen.

First page of the inspection report

Accessibility

AspectRatio renders a plain div and adds no semantics and no keyboard interaction.

You provide:

  • A text alternative for the media inside: the alt attribute 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 width and height on the element.

Content

  • Pick one ratio for a set of items, and keep it.
  • Crop with object-cover. Use object-contain when cropping would hide something that matters, such as a label on a part.
Photo of the Brescia site
Do

Fill the box with media or a placeholder of the same shape.

The Brescia site runs two production lines on one shift, and Marco reviews the output every Friday afternoon with the quality team.
Don’t

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.

PropTypeDefaultDescription
rationumberNoneWidth divided by height, for example 16 / 9.
className?stringNoneClasses merged after the base classes.