GitHub

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-ratio
01

Live Demo

Explore all variants and interactive states in Storybook.

Open Storybookopen_in_new

Common Aspect Ratios

16:9 - Widescreen

16:9 landscape

4:3 - Standard TV

4:3 landscape

1:1 - Square

1:1 square

21:9 - Ultrawide

21:9 ultrawide

Responsive Grid

Grid item 1
Grid item 2
Grid item 3
Grid item 4
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.

PropTypeDefaultDescription
rationumber | stringWidth-to-height ratio (e.g. 16/9, 4/3, 1). Can be a number (decimal) or string (fraction).
childrenReactNodeContent to display inside the container (image, video, iframe, etc.).
classNamestringAdditional CSS classes to apply (merged with base styles).
React Principles