Aspect Ratio
Constrains content to a desired width-to-height ratio.
Powered by
Installation
bash
npx shadcn@latest add @redpanda/aspect-ratiobash
pnpm dlx shadcn@latest add @redpanda/aspect-ratiobash
yarn dlx shadcn@latest add @redpanda/aspect-ratiobash
bunx shadcn@latest add @redpanda/aspect-ratiobash
nubx shadcn@latest add @redpanda/aspect-ratiobash
aube dlx shadcn@latest add @redpanda/aspect-ratioWhen to use
Use AspectRatio when content (images, video embeds, maps, placeholders) must keep a fixed proportion regardless of the container width. The component reserves the correct height up front, which prevents layout shift while media loads.
Usage
tsx
import { AspectRatio } from '@/components/redpanda-ui/aspect-ratio';tsx
<AspectRatio ratio={16 / 9} className="overflow-hidden rounded-lg bg-surface-subtle"> <img alt="Photo of a redpanda" className="h-full w-full object-cover" src="/images/redpanda.jpg" /></AspectRatio>Anatomy
The AspectRatio component is a plain container styled with the CSS aspect-ratio property:
plaintext
AspectRatio├── Base element (div, relative positioning)├── --ratio custom property - set from the ratio prop├── aspect-(--ratio) - CSS aspect-ratio driven sizing└── children - fill the box (use h-full w-full or absolute inset-0)The container is relative, so children can use absolute inset-0 (or h-full w-full) to fill it. Add overflow-hidden plus a radius on the AspectRatio itself when clipping media to rounded corners.
Examples
Common Ratios
tsx
<AspectRatio ratio={1}>{/* square */}</AspectRatio><AspectRatio ratio={4 / 3}>{/* standard */}</AspectRatio><AspectRatio ratio={16 / 9}>{/* widescreen */}</AspectRatio>Props
| Prop | Type | Default | Description |
|---|---|---|---|
ratio |
number |
— | Width-to-height ratio of the container (e.g. 16 / 9) |
className |
string |
— | Additional CSS classes |
testId |
string |
— | Value applied to data-testid for testing |
All other props are forwarded to the underlying div element.
Accessibility
- AspectRatio is purely presentational and adds no semantics or keyboard interactions.
- Provide meaningful
alttext on images rendered inside the container.
Credits
- We take our inspiration from Shadcn UI for the aspect ratio component.