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-ratioComplete the Installation guide first. Then copy the component files below.
No extra packages are required.
Copy the files
src/components/ui/aspect-ratio/aspect-ratio.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
export { default as AspectRatio } from './aspect-ratio.astro'
export type { AspectRatioProps } from './types.ts'
src/components/ui/aspect-ratio/types.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
}
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.

