Skip to main content

Aspect Ratio

Keep a box at a fixed proportion for images, video and embeds.

Office at golden hour
1import { AspectRatio } from '@/components/ui/aspect-ratio';
2
3export function Default() {
4 return (
5 <div className="w-full max-w-md">
6 <AspectRatio ratio={16 / 9} className="rounded-xl">
7 <img src="https://picsum.photos/seed/aspect/960/540" alt="Office at golden hour" />
8 </AspectRatio>
9 </div>
10 );
11}

Installation

pnpm dlx nachui add aspect-ratio

Anatomy

1import { AspectRatio } from '@/components/ui/aspect-ratio';
1<AspectRatio ratio={16 / 9} className="rounded-lg">
2 <img src="/cover.jpg" alt="Cover" />
3</AspectRatio>
The box takes the full width of its parent and derives its height from ratio through the CSS aspect-ratio property, so nothing jumps while the media loads. A direct img or video child fills the box with object-cover, and an iframe is stretched to cover it.

Examples

Default

Office at golden hour
1import { AspectRatio } from '@/components/ui/aspect-ratio';
2
3export function Default() {
4 return (
5 <div className="w-full max-w-md">
6 <AspectRatio ratio={16 / 9} className="rounded-xl">
7 <img src="https://picsum.photos/seed/aspect/960/540" alt="Office at golden hour" />
8 </AspectRatio>
9 </div>
10 );
11}

Ratios

Any number works: 1, 4 / 3, 3 / 4, 21 / 9.
1 / 1
4 / 3
3 / 4
21 / 9
1import { AspectRatio } from '@/components/ui/aspect-ratio';
2
3const ratios = [
4 { label: '1 / 1', value: 1 },
5 { label: '4 / 3', value: 4 / 3 },
6 { label: '3 / 4', value: 3 / 4 },
7 { label: '21 / 9', value: 21 / 9 },
8];
9
10export function Ratios() {
11 return (
12 <div className="grid w-full max-w-md grid-cols-2 gap-4">
13 {ratios.map((ratio) => (
14 <div key={ratio.label} className="flex flex-col gap-1.5">
15 <AspectRatio
16 ratio={ratio.value}
17 className="border-border bg-hatch text-muted-foreground flex items-center justify-center rounded-lg border"
18 >
19 <span className="font-mono text-xs">{ratio.label}</span>
20 </AspectRatio>
21 </div>
22 ))}
23 </div>
24 );
25}

API Reference

AspectRatio

PropTypeDefaultDescription
rationumber16 / 9Width divided by height
asReact.ElementType'div'Element to render
classNamestring-Additional CSS classes, rounding goes here
Found something to improve?

Notice a bug, typo, or missing detail on this page? Help us make the documentation better by opening a GitHub issue.

Create an Issue
Ctrl+I