Skip to content
Esc
↑↓navigate↵open⌘Jpreview
On this page

Aspect Ratio for Astro

Astro containers that keep media and embeds at a chosen width-to-height ratio.

Sample landscape

Installation

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

Usage

import { AspectRatio } from "@/components/ui/aspect-ratio"
<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.

Sample landscape

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

PropType
rationumber

Width divided by height. Common values include `16 / 9`, `4 / 3`, `1`, `9 / 16`, and `21 / 9`.

Typenumber

Read the installed source 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.