---
title: Aspect Ratio for Astro
description: "Astro containers that keep media and embeds at a chosen width-to-height ratio."
seo:
    title: Aspect Ratio for Astro | Shadcn & Tailwind CSS
related:
    - /components/card
    - /components/video
    - /components/image-compare
sidebar:
    label: "Aspect Ratio"
---

```astro
---
import { Image } from "astro:assets"

import { AspectRatio } from "@/components/ui/aspect-ratio"
import image from "@/assets/wizard/wizard-on-moon.jpeg"
---

<AspectRatio ratio={16 / 9} class="w-full max-w-3xl">
  <Image
    src={image}
    alt="Sample landscape"
    class="size-full rounded-md object-cover"
  />
</AspectRatio>
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/aspect-ratio
```

### Manual

Complete the [Installation guide](/docs/installation) first. Then copy the component files below.

No extra packages are required.

#### src/components/ui/aspect-ratio/aspect-ratio.astro

```astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"
import type { AspectRatioProps } from "./types.ts"

/** Div attributes pass through. */
type Props = HTMLAttributes<"div"> & AspectRatioProps

const { class: className, ratio, style: styleProp, ...props } = Astro.props

if (!Number.isFinite(ratio) || ratio <= 0) {
  throw new RangeError("AspectRatio needs a finite ratio greater than zero.")
}

const style =
  typeof styleProp === "string"
    ? `--ratio: ${ratio}; ${styleProp}`
    : {
        "--ratio": ratio,
        ...(styleProp ? styleProp : {}),
      }
---

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

#### src/components/ui/aspect-ratio/index.ts

```ts
export { default as AspectRatio } from './aspect-ratio.astro'

export type { AspectRatioProps } from './types.ts'
```

#### src/components/ui/aspect-ratio/types.ts

```ts
/**
 * Props for a box that keeps a fixed width-to-height ratio.
 * Div attributes such as `class` and `id` pass through on the component.
 */
export interface AspectRatioProps {
    /**
     * Width divided by height.
     *
     * Common values include `16 / 9`, `4 / 3`, `1`, `9 / 16`, and `21 / 9`.
     */
    ratio: number
}
```

Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.


## Usage

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

```astro
<AspectRatio ratio={16 / 9} class="w-full max-w-3xl">
  <img src="/photo.jpg" alt="Landscape" class="size-full rounded-md object-cover" />
</AspectRatio>
```

Pass width divided by height. Common values are `16 / 9`, `4 / 3`, `1`, `9 / 16`, and `21 / 9`.

## Example

### Aspect Ratio with Toggle Group

Pair the aspect ratio component with a toggle group to allow users to select different views of the same image.

```astro
---
import { Image } from "astro:assets"

import { AspectRatio } from "@/components/ui/aspect-ratio"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import image from "@/assets/wizard/wizard-looking-out-of-cave.png"

const ratios = {
  "16:9": 16 / 9,
  "4:3": 4 / 3,
  "1:1": 1,
  "9:16": 9 / 16,
  "21:9": 21 / 9,
} as const
---

<div
  class="flex w-full max-w-2xl flex-col gap-4 justify-center items-center"
  data-aspect-ratio-demo
  data-ratios={JSON.stringify(ratios)}
>
  <ToggleGroup defaultValue="16:9" aria-label="Aspect ratio" variant="outline">
    {Object.entries(ratios).map(([label]) => (
      <ToggleGroupItem value={label}>{label}</ToggleGroupItem>
    ))}
  </ToggleGroup>
  <!-- The 16:9 stage keeps its first size. The frame fits inside that box. -->
  <div
    class="flex aspect-video w-full items-center justify-center overflow-hidden rounded-md bg-muted @container-size"
    data-aspect-ratio-stage
  >
    <AspectRatio
      ratio={16 / 9}
      class="h-auto w-[min(100cqw,calc(100cqh*var(--ratio)))]"
    >
      <Image
        src={image}
        alt="Sample landscape"
        class="size-full rounded-md object-cover"
      />
    </AspectRatio>
  </div>
</div>

<script>
  /**
   * `@data-slot/toggle-group` dispatches `toggle-group:change` on the group
   * root. The event bubbles, and `detail.value` is the selected item values.
   * Preview pages rename `id`, so this demo finds its parts by slot.
   */
  const ratioFor = (demo: HTMLElement, value: string): number | undefined => {
    try {
      const ratios = JSON.parse(demo.dataset.ratios ?? "") as Record<
        string,
        number
      >
      const ratio = ratios[value]
      return Number.isFinite(ratio) ? ratio : undefined
    } catch {
      return undefined
    }
  }

  const handleChange = (event: HTMLElementEventMap["toggle-group:change"]) => {
    const group = event.currentTarget
    if (!(group instanceof HTMLElement)) return

    const demo = group.closest<HTMLElement>("[data-aspect-ratio-demo]")
    const frame = demo?.querySelector<HTMLElement>('[data-slot="aspect-ratio"]')
    const value = event.detail.value[0]
    if (!demo || !frame || !value) return

    const ratio = ratioFor(demo, value)
    if (ratio === undefined) return
    frame.style.setProperty("--ratio", String(ratio))
  }

  const attach = () => {
    document
      .querySelectorAll<HTMLElement>(
        '[data-aspect-ratio-demo] [data-slot="toggle-group"]',
      )
      .forEach((group) => {
        if (group.dataset.ratioDemoBound) return
        group.dataset.ratioDemoBound = ""
        group.addEventListener("toggle-group:change", handleChange)
      })
  }

  attach()
  document.addEventListener("astro:page-load", attach)
</script>
```

## Notes

- Set `ratio` to width divided by height. Portrait frames use values below `1`.
- Give slotted media `size-full` and `object-cover` when it should fill the box.
- The container is `position: relative` so absolutely positioned children can fill it.

## API Reference

### AspectRatioProps

<AutoTypeTable
    path="../../packages/ui/src/components/ui/aspect-ratio/types.ts"
    name="AspectRatioProps"
/>

Read the [installed source](/r/aspect-ratio.json) for the complete prop types.

## When to use Aspect Ratio

Use Aspect Ratio when width is fluid but height must follow a known proportion. It reserves space before images load and keeps grids aligned.

## Keyboard and behavior

Aspect Ratio does not crop or scale content by itself. Pair it with `object-cover` or layout utilities on the child.

## Theme and layout

The box inherits width from its parent. Constrain width with utilities such as `max-w-md` when a portrait frame should stay narrow.
