Aspect Ratio

Holds content to a fixed width-to-height ratio.

16 / 9
import { AspectRatio } from '@/components/ui/aspect-ratio'

export default function AspectRatioDemo() {
  return (
    <div className="w-full max-w-md">
      <AspectRatio ratio={16 / 9} className="rounded-lg border border-border bg-muted">
        <div className="flex size-full items-center justify-center bg-[linear-gradient(135deg,var(--muted),var(--accent))] font-mono text-sm text-muted-foreground">
          16 / 9
        </div>
      </AspectRatio>
    </div>
  )
}

Installation

pnpm dlx shadcn@latest add https://kagadmodyaa.vercel.app/r/aspect-ratio.json

Needs a React + Tailwind project set up with shadcn. Copies the component source straight into your project, so you can edit it.

Aspect Ratio imports cn() from lib/utils.ts — add it too if you don't have it yet:

import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

Usage

import { AspectRatio } from '@/components/ui/aspect-ratio'

<AspectRatio ratio={16 / 9} className="rounded-lg">
  <img src="/cover.jpg" alt="Cover" />
</AspectRatio>

Examples

Common ratios

1 / 1
4 / 3
16 / 9
21 / 9
import { AspectRatio } from '@/components/ui/aspect-ratio'

const ratios = [
  { label: '1 / 1', value: 1 },
  { label: '4 / 3', value: 4 / 3 },
  { label: '16 / 9', value: 16 / 9 },
  { label: '21 / 9', value: 21 / 9 },
]

export default function AspectRatioRatios() {
  return (
    <div className="grid w-full max-w-lg grid-cols-2 items-end gap-4">
      {ratios.map(ratio => (
        <AspectRatio key={ratio.label} ratio={ratio.value} className="rounded-md border border-border bg-muted">
          <div className="flex size-full items-center justify-center font-mono text-xs text-muted-foreground">{ratio.label}</div>
        </AspectRatio>
      ))}
    </div>
  )
}

API Reference

NameTypeDefaultDescription
rationumber1Width divided by height, e.g. 16 / 9. Applied with the CSS aspect-ratio property.
classNamestring—Extra classes for the box. It fills the width of its parent; set a width to constrain it.