Aspect Ratio for Astro
Astro containers that keep media and embeds at a chosen width-to-height ratio.
Installation
bunx --bun shadcn@latest add @gnostic/aspect-rationpx shadcn@latest add @gnostic/aspect-ratiopnpm dlx shadcn@latest add @gnostic/aspect-ratioCopy the files
src/components/ui/aspect-ratio/aspect-ratio.astrosrc/components/ui/aspect-ratio/index.tssrc/components/ui/aspect-ratio/types.ts
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.
Notes
- Set
ratioto width divided by height. Portrait frames use values below1. - Give slotted media
size-fullandobject-coverwhen it should fill the box. - The container is
position: relativeso absolutely positioned children can fill it.
API Reference
AspectRatioProps
rationumber
Width divided by height. Common values include `16 / 9`, `4 / 3`, `1`, `9 / 16`, and `21 / 9`.
numberRead 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.

