# Aspect Ratio

> A box that keeps its shape before its picture loads, such as a 16:9 video frame.

Page: https://uicontext.com/docs/components/aspect-ratio

Group: Primitives.

## When to use

A box that keeps its shape before its picture loads, such as a 16:9 video frame. Use [Masonry](https://uicontext.com/docs/components/masonry.md) instead when the pictures keep their own heights in a wall.

## Usage

```ts
import { AspectImage } from "./ui/uicontext/components/AspectRatio.ts"

export const Cover = <M>(h: Html.H<M>, url: string) => AspectImage(h, { ratio: "16 / 9", src: url, alt: "Team offsite, Lisbon", shape: "rounded" })
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### Product photos, all square

The example the page opens with: Aspect Ratio in “Product photos, all square”.

```ts title="src/demo.ts" source="www/src/examples/aspect-ratio/demo.ts"
import type { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { AspectImage } from "./ui/uicontext/components/AspectRatio.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, font, space } from "./ui/uicontext/components/tokens.stylex.ts"
import { picture } from "./pictures.ts"

const styles = stylex.create({
	grid: { display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(9rem, 1fr))", gap: space.lg, inlineSize: "min(100%, 40rem)", margin: 0, padding: 0, listStyle: "none" },
	item: { display: "grid", gap: space.sm },
	name: { fontSize: font.sm, fontWeight: 500, color: color.fg, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
	price: { fontSize: font.sm, color: color.muted, fontVariantNumeric: "tabular-nums" },
})

const products = [
	{ name: "Linen apron, oat", price: "$48", photo: picture(800, 1000, 0) },
	{ name: "Stoneware mug", price: "$22", photo: picture(1200, 800, 1) },
	{ name: "Walnut serving board", price: "$64", photo: "" },
	{ name: "Cast iron grill pan", price: "$85", photo: picture(1000, 1000, 3) },
]

// a shop's product grid: photos of any shape cropped to the same square, and one still missing
export const ProductGrid = <M>(h: Html.H<M>) =>
	h.ul.attrs(sx(styles.grid)).children(
		products.map((p) =>
			h.li.key(p.name).attrs(sx(styles.item)).children(
				AspectImage(h, { ratio: "1", src: p.photo, alt: p.name, shape: "rounded" }),
				h.span.attrs(sx(styles.name)).children(p.name),
				h.span.attrs(sx(styles.price)).children(p.price),
			)),
	)
```

### A video frame and a round avatar

`AspectRatio` takes anything; give it a poster now and the player later, and the page doesn't move.

```ts title="src/video.ts" source="www/src/examples/aspect-ratio/video.ts"
import type { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { AspectImage, AspectRatio } from "./ui/uicontext/components/AspectRatio.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, corner, font, space } from "./ui/uicontext/components/tokens.stylex.ts"
import { picture } from "./pictures.ts"

const styles = stylex.create({
	wrap: { display: "grid", gap: space.lg, inlineSize: "min(100%, 36rem)" },
	poster: { position: "relative", display: "grid", placeItems: "center", gridRow: "1", gridColumn: "1" },
	image: { gridRow: "1", gridColumn: "1", inlineSize: "100%", blockSize: "100%", objectFit: "cover" },
	play: {
		gridRow: "1",
		gridColumn: "1",
		display: "inline-flex",
		alignItems: "center",
		gap: space.sm,
		blockSize: 44,
		paddingInline: space.lg,
		borderWidth: 0,
		borderRadius: corner.pill,
		backgroundColor: "rgb(0 0 0 / 0.62)",
		color: "white",
		fontFamily: "inherit",
		fontSize: font.sm,
		fontWeight: 600,
		cursor: "pointer",
		outline: { default: "none", ":focus-visible": "2px solid white" },
		outlineOffset: 2,
	},
	row: { display: "grid", gridTemplateColumns: "auto minmax(0, 1fr)", alignItems: "center", gap: space.md },
	thumb: { inlineSize: 64 },
	who: { fontSize: font.sm, color: color.fg },
})

// a course lesson: the video's 16:9 frame holds its room before the player loads, and a round
// avatar is a 1:1 box with the circle shape
export const LessonVideo = <M>(h: Html.H<M>) =>
	h.div.attrs(sx(styles.wrap)).children(
		AspectRatio(h, {
			ratio: "16 / 9",
			shape: "rounded",
			children: [
				h.img.attrs({ src: picture(1600, 900, 1), alt: "", ...sx(styles.image) }),
				h.div.attrs(sx(styles.poster)).children(h.button.attrs({ type: "button", ...sx(styles.play) }).children(h.span.attrs({ "aria-hidden": "true" }).children("▶ "), "Play lesson 4 · 12:04")),
			],
		}),
		h.div.attrs(sx(styles.row)).children(AspectImage(h, { ratio: "1", src: picture(400, 400, 3), alt: "", shape: "circle", style: styles.thumb }), h.span.attrs(sx(styles.who)).children("Lesson 4 · Priya Raman")),
	)
```

### Sample data

The examples above import these files.

```ts title="src/pictures.ts" source="www/src/examples/_shared/pictures.ts"
// Pictures drawn inline, so examples need no image files: a sky, a sun and two hills in a palette,
// at the photo's own width and height.

const palettes = [
	["#fde68a", "#f97316", "#7c2d12", "#431407"],
	["#bae6fd", "#38bdf8", "#0f766e", "#134e4a"],
	["#e9d5ff", "#a855f7", "#4c1d95", "#2e1065"],
	["#fecdd3", "#fb7185", "#9f1239", "#4c0519"],
	["#d9f99d", "#84cc16", "#365314", "#1a2e05"],
	["#e2e8f0", "#94a3b8", "#334155", "#0f172a"],
] as const

/** A landscape picture `width` × `height`, in palette `tone` (0–5). */
export const picture = (width: number, height: number, tone: number) => {
	const [sky, sun, near, far] = palettes[tone % palettes.length]!
	const w = width
	const h = height
	return `data:image/svg+xml,${encodeURIComponent(
		`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" preserveAspectRatio="xMidYMid slice"><rect width="${w}" height="${h}" fill="${sky}"/><circle cx="${w * 0.7}" cy="${h * 0.35}" r="${Math.min(w, h) * 0.14}" fill="${sun}"/><path d="M0 ${h * 0.72} Q${w * 0.3} ${h * 0.5} ${w * 0.6} ${h * 0.7} T${w} ${h * 0.62} V${h} H0Z" fill="${far}" fill-opacity="0.55"/><path d="M0 ${h * 0.86} Q${w * 0.4} ${h * 0.7} ${w} ${h * 0.84} V${h} H0Z" fill="${near}"/></svg>`,
	)}`
}
```

## API reference

### AspectRatio (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `ratio` (required) | `string` | The shape, as CSS writes it: "16 / 9", "4 / 3", "1". |
| `children` (required) | `View.Children` | What fills the box; give an image or iframe `aspectFill` so it fills it. |
| `shape` | `"rounded" \| "circle"` | Rounded corners, or a circle for a square box. |
| `style` | `Style` | — |

### AspectImage (view function)

**Options**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `ratio` (required) | `string` | — | — |
| `src` | `string` | — | Left out, or empty, while there's no picture: a placeholder says what it was. |
| `alt` (required) | `string` | — | What the picture shows; empty for one that only decorates. |
| `fit` | `"cover" \| "contain"` | — | — |
| `shape` | `"rounded" \| "circle"` | — | — |
| `loading` | `"lazy" \| "eager"` | `"lazy"` | "lazy" by default: the box keeps the room until it scrolls near. |
| `style` | `Style` | — | — |

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/aspect-ratio
```

With npm: `npx shadcn@latest add checkfu/uicontext/aspect-ratio`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/aspect-ratio`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/aspect-ratio`.

It writes these files:

- `src/ui/uicontext/components/AspectRatio.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/AspectRatio.ts](https://github.com/checkfu/uicontext/blob/main/src/AspectRatio.ts)

## Related

- [Button](https://uicontext.com/docs/components/button.md) (`button`): A button, and a link that looks like one, in every tone and three sizes.
- [Toggle](https://uicontext.com/docs/components/toggle.md) (`toggle`): A button that stays pressed, such as Bold or Pin.
- [Toggle Group](https://uicontext.com/docs/components/toggle-group.md) (`toggle-group`): Buttons that stay pressed and share one value, such as text styles.
- [Input](https://uicontext.com/docs/components/input.md) (`input`): Text inputs, selects and textareas in a labeled field with a hint and an error, and their styles for controls you lay out yourself.
- [Status](https://uicontext.com/docs/components/status.md) (`status`): Status badges and tags for runs and records.
- [Glyphs](https://uicontext.com/docs/components/glyphs.md) (`glyphs`): Small marks for status, priority, color and people.
