# Aspect Ratio

Displays content within a desired ratio.

## When to use

* Keep an image or video at a fixed ratio, such as 16:9, while its width changes.
* Reserve the space of media before it loads, so the layout does not shift.

## How it works

One part: `AspectRatio`, with a `ratio` prop. With Base UI it is a plain `div` styled with the ratio; with Radix it wraps `AspectRatio` from `radix-ui`. The official example uses `next/image`; this site does not run Next.js, so the demo uses `<img>`.

## Example

### Base UI

```tsx
'use client'

// next/image replaced by <img>: this site does not run Next.js.

import { AspectRatio } from "@/shadcn/base/ui/aspect-ratio"

export default function AspectRatioDemo() {
  return (
    <AspectRatio ratio={16 / 9} className="w-full max-w-sm rounded-lg bg-muted">
      <img
        src="https://avatar.vercel.sh/shadcn1"
        alt="Photo"
        className="size-full rounded-lg object-cover grayscale dark:brightness-20"
      />
    </AspectRatio>
  )
}
```

```tsx [components/ui/aspect-ratio.tsx]
import { cn } from "cn"

function AspectRatio({
  ratio,
  className,
  ...props
}: React.ComponentProps<"div"> & { ratio: number }) {
  return (
    <div
      data-slot="aspect-ratio"
      style={
        {
          "--ratio": ratio,
        } as React.CSSProperties
      }
      className={cn("relative aspect-(--ratio)", className)}
      {...props}
    />
  )
}

export { AspectRatio }
```

### Radix

```tsx
'use client'

// next/image replaced by <img>: this site does not run Next.js.

import { AspectRatio } from "@/shadcn/radix/ui/aspect-ratio"

export default function AspectRatioDemo() {
  return (
    <div className="w-full max-w-sm">
      <AspectRatio ratio={16 / 9} className="rounded-lg bg-muted">
        <img
          src="https://avatar.vercel.sh/shadcn1"
          alt="Photo"
          className="w-full rounded-lg object-cover grayscale dark:brightness-20"
        />
      </AspectRatio>
    </div>
  )
}
```

```tsx [components/ui/aspect-ratio.tsx]
"use client"

import { AspectRatio as AspectRatioPrimitive } from "radix-ui"

function AspectRatio({
  ...props
}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
  return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />
}

export { AspectRatio }
```

## Installation

```bash
npx shadcn@latest add aspect-ratio
```

## Reference

Official page: https://ui.shadcn.com/docs/components/aspect-ratio
