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/aria/aspect-ratio.jsonnpx shadcn@latest add https://kit.dev/r/aria/aspect-ratio.jsonpnpm dlx shadcn@latest add https://kit.dev/r/aria/aspect-ratio.jsonyarn shadcn@latest add https://kit.dev/r/aria/aspect-ratio.jsonCopy and paste the following code into your project.
import type React from "react";
import { cn } from "@/lib/utils";
interface AspectRatioProps extends React.ComponentProps<"div"> {
ratio?: number;
}
export const AspectRatio = (props: AspectRatioProps) => {
const { ratio = 1, className, style, ...rest } = props;
return (
<div
className={cn("relative aspect-(--ratio)", className)}
data-slot="aspect-ratio"
style={{ "--ratio": ratio, ...style } as React.CSSProperties}
{...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
AttributeType
CSS variableType
--ratiostring