Aspect Ratio

Displays content within a desired ratio.

Photo by Drew Beamer

Installation

Install the following dependencies.

pnpm add @radix-ui/react-aspect-ratio

Copy and paste the following code into your project.

"use client";

import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio";

const AspectRatio = AspectRatioPrimitive.Root;

export { AspectRatio };

Update the import paths to match your project setup.

Usage

import Image from "next/image";
 
import { AspectRatio } from "~/components/ui/AspectRatio";
<AspectRatio ratio={16 / 9} className="overflow-hidden rounded-2 bg-muted">
  <Image
    src="https://images.unsplash.com/photo-1715412406818-48241c841c9e?q=80&w=2828&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
    alt="Photo by Drew Beamer"
    fill
    className="object-cover"
  />
</AspectRatio>

Examples

Next.js Image

Have <AspectRatio> define the size of the image, and add the fill prop and object-cover class to <Image>.

Photo by Drew Beamer