shadcn.io is not affiliated with official shadcn/ui
Shadcn Aspect Ratio for React
Wrapper that maintains aspect ratio for content.
Installation
bunx --bun shadcn@latest add https://kit.dev/r/radix/aspect-ratio.jsonnpx shadcn@latest add https://kit.dev/r/radix/aspect-ratio.jsonpnpm dlx shadcn@latest add https://kit.dev/r/radix/aspect-ratio.jsonyarn shadcn@latest add https://kit.dev/r/radix/aspect-ratio.jsonInstall the following dependencies:
bun add radix-uinpm install radix-uipnpm add radix-uiyarn add radix-uiCopy and paste the following code into your project.
"use client";
import { AspectRatio as AspectRatioPrimitive } from "radix-ui";
import type React from "react";
import { cn } from "@/lib/utils";
export const AspectRatio = (
props: React.ComponentProps<typeof AspectRatioPrimitive.Root>
) => {
const { className, ...rest } = props;
return (
<AspectRatioPrimitive.Root
className={cn("relative", className)}
data-slot="aspect-ratio"
{...rest}
/>
);Update the import paths to match your project setup.
Usage
import { AspectRatio } from "@/components/ui/aspect-ratio";<AspectRatio className="w-full max-w-sm rounded-lg bg-muted" ratio={16 / 9}>
<img
alt="Photo"
className="absolute inset-0 size-full rounded-lg object-cover grayscale dark:brightness-20"
height={900}
src="https://avatar.vercel.sh/shadcn1"
width={1600}
/>
</AspectRatio>Demos
Square
A square aspect ratio component using the ratio={1 / 1} prop. This is useful for displaying images in a square format.
Portrait
A portrait aspect ratio component using the ratio={9 / 16} prop. This is useful for displaying images in a portrait format.
Rtl
Right-to-left aspect ratio. See the RTL configuration guide for document direction.
API Reference
AspectRatio
PropType
ratio?numberAttributeType