Installation
npx shadcn@latest add aspect-ratio
yarn dlx shadcn@latest add aspect-ratio
pnpm dlx shadcn@latest add aspect-ratio
Usage
import { AspectRatio } from "@/components/ui/aspect-ratio"
<AspectRatio ratio={16 / 9}>
<img src="/photo.jpg" alt="Photo" />
</AspectRatio>
Component Code
"use client"
import { AspectRatio as AspectRatioPrimitive } from "radix-ui"
function AspectRatio({
...props
}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />
}
export { AspectRatio }
Examples
- Image
- Video
- Custom Ratio
Display an image within a 16:9 aspect ratio.
<div className="w-full max-w-md">
<AspectRatio ratio={16 / 9}>
<img
src="/placeholder.jpg"
alt="Placeholder"
className="rounded-md object-cover w-full h-full"
/>
</AspectRatio>
</div>
Embed a video with a specific aspect ratio.
<AspectRatio ratio={16 / 9}>
<iframe
src="https://www.youtube.com/embed/dQw4w9WgXcQ"
className="w-full h-full"
allowFullScreen
/>
</AspectRatio>
Use different aspect ratios like 1:1 or 4:3.
<AspectRatio ratio={1}>
<img
src="/square.jpg"
alt="Square image"
className="rounded-md object-cover w-full h-full"
/>
</AspectRatio>
API Reference
AspectRatio
| Prop | Type | Default |
|---|---|---|
ratio | number | 1 |
className | string | - |