Aspect Ratio
A container component that maintains a specific width-to-height ratio for its child elements, commonly used for images, videos, or embeds to prevent layout shifts.
This preview shows how the Aspect Ratio component maintains the proportions of its content (in this case, an image) even when the container size changes.
Installation
To use the Aspect Ratio component in your project, you need to install it. You have two options: using the CLI (Command Line Interface) for a quick setup, or following the Manual steps for more control and understanding.
The CLI command is the easiest way to add the Aspect Ratio component. It automatically handles downloading the necessary code and dependencies for you. Running this command in your project's terminal will add the aspect-ratio component files.
npx shadcn@latest add aspect-ratioUsage
Once installed, import the AspectRatio component and use it to wrap the content you want to constrain.
Here's how to use it:
Wrap your content (like an
Image,iframe, orvideo) with the<AspectRatio>component.Provide the desired
ratioas a prop. This is calculated aswidth / height. For example,16 / 9for a widescreen ratio or1for a square.The component will automatically adjust its height based on its width to maintain the specified ratio.
<div className="w-[450px]">
<AspectRatio ratio={16 / 9} className="bg-muted">
<Image
src="https://images.unsplash.com/photo-1634912314704-c646c586b131?q=80&w=1470&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
alt="Photo by James A. Molnar"
fill // Use Next.js Image fill prop for responsiveness within AspectRatio
className="rounded-md object-cover"
/>
</AspectRatio>
</div>