# Aspect Ratio

Displays content within a desired aspect ratio.

## Installation

```bash
npx shadcn@latest add https://reactdocs.canceydejean.dev/r/aspect-ratio.json
```

[Registry JSON](https://reactdocs.canceydejean.dev/r/aspect-ratio.json)

## Preview

```tsx
import { AspectRatio } from "@/components/ui/aspect-ratio/aspect-ratio";

export function Preview() {
  return (
    <AspectRatio ratio={16 / 9} className="w-full max-w-md overflow-hidden rounded-lg bg-muted">
      <img
        src="https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80"
        alt="Mountain landscape by Drew Beamer"
        className="size-full object-cover dark:brightness-50 dark:grayscale"
      />
    </AspectRatio>
  );
}
```


## Source

### aspect-ratio.tsx

```tsx
import type * as React from "react";

import { cn } from "cn";

function AspectRatio({
  ratio,
  className,
  style,
  ...props
}: React.ComponentProps<"div"> & { ratio: number }) {
  const aspectStyle: React.CSSProperties & { "--ratio": number } = {
    ...style,
    "--ratio": ratio,
  };

  return (
    <div
      data-slot="aspect-ratio"
      style={aspectStyle}
      className={cn("relative aspect-(--ratio)", className)}
      {...props}
    />
  );
}

export { AspectRatio };
```



## Usage

Use aspect ratio to constrain media and placeholders so layout does not shift as content loads.

```tsx
import { AspectRatio } from "@/components/aspect-ratio/aspect-ratio";

export function Example() {
  return (
    <AspectRatio ratio={16 / 9} className="bg-muted overflow-hidden rounded-lg">
      <img
        src="https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80"
        alt="Mountain landscape by Drew Beamer"
        className="size-full object-cover"
      />
    </AspectRatio>
  );
}
```

Pass `ratio` as a number (for example `16 / 9`, `1`, or `4 / 3`).

