Aspect Ratio
Container that enforces a fixed aspect ratio for responsive content. Maintains proportions at any screen size, preventing layout shift during page load.
ResponsiveNo Layout ShiftSimple APIModern CSSVersatile
Install
$
npx react-principles add aspect-ratio01
Live Demo
Explore all variants and interactive states in Storybook.
Open Storybookopen_in_newCommon Aspect Ratios
16:9 - Widescreen
4:3 - Standard TV
1:1 - Square
21:9 - Ultrawide
Responsive Grid
02
Code Snippet
src/ui/AspectRatio.tsx
import { AspectRatio } from "@/ui/AspectRatio"; // Basic usage <AspectRatio ratio={16 / 9}> <img src="/video-poster.jpg" alt="Video thumbnail" className="w-full h-full object-cover" /> </AspectRatio> // Square ratio <AspectRatio ratio={1}> <img src="/avatar.jpg" alt="Profile picture" className="w-full h-full object-cover" /> </AspectRatio> // String ratio <AspectRatio ratio="21/9"> <img src="/ultrawide.jpg" alt="Cinematic shot" className="w-full h-full object-cover" /> </AspectRatio>
03
Copy-Paste (Single File)
AspectRatio.tsx
import { cn } from "@/lib/utils"; // ─── Types ──────────────────────────────────────────────────────────────────── export interface AspectRatioProps { ratio: number | string; children: React.ReactNode; className?: string; } // ─── Helpers ──────────────────────────────────────────────────────────────── function parseRatio(ratio: number | string): string { if (typeof ratio === "number") { return `${ratio} / 1`; } return ratio; } // ─── Component ──────────────────────────────────────────────────────────────── export function AspectRatio({ ratio, children, className }: AspectRatioProps) { const aspectRatio = parseRatio(ratio); return ( <div className={cn("relative w-full overflow-hidden", className)} style={{ aspectRatio }} > {children} </div> ); }
04
Props
Simple container component that maintains aspect ratio for responsive content.
| Prop | Type | Default | Description |
|---|---|---|---|
ratio | number | string | — | Width-to-height ratio (e.g. 16/9, 4/3, 1). Can be a number (decimal) or string (fraction). |
children | ReactNode | — | Content to display inside the container (image, video, iframe, etc.). |
className | string | — | Additional CSS classes to apply (merged with base styles). |