# Aspect Ratio

> Hold media to a fixed width-to-height ratio so layouts do not shift while it loads.

Source: https://www.honestui.com/docs/components/aspect-ratio

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

export function AspectRatioDemo() {
  return (
    <figure className="m-0 w-full max-w-md">
      <AspectRatio
        ratio={16 / 9}
        className="rounded-[var(--hui-radius-3)] bg-[var(--hui-color-background-base-secondary)]"
      >
        <img
          src="https://picsum.photos/1280/720?grayscale&random=31"
          alt="Grayscale landscape with hills under an overcast sky"
          width={1280}
          height={720}
        />
      </AspectRatio>
      <figcaption className="mt-[var(--hui-space-2)] text-[var(--hui-color-foreground-base-secondary)] [font-size:var(--hui-font-size-small)]">
        The 16:9 box reserves its height before the image loads.
      </figcaption>
    </figure>
  )
}

```

## Overview [#overview]

Use Aspect Ratio to give an image, video, embed, or placeholder a predictable shape. The box takes its height from its width, so it reserves the right space before media arrives. Pages stop jumping as images load, and cards in a grid line up even when their source images have different dimensions.

It is a single element with the CSS `aspect-ratio` property. Older libraries used a padding-top percentage and an absolutely positioned child to fake the same thing; every current browser supports the property directly, so there is no wrapper, no positioning trick, and no extra markup.

## Anatomy [#anatomy]

`AspectRatio` renders one `div` with `aspect-ratio` set from the `ratio` prop and `overflow: hidden`. A direct `img`, `video`, or `iframe` child fills the box automatically: images and videos use `object-fit: cover`, and iframes lose their default border. Any other content, such as a placeholder label or a chart, is laid out normally inside the box.

## Choosing a ratio [#choosing-a-ratio]

Pass the ratio as width divided by height. Writing it as a fraction keeps the intent readable: `16 / 9` for video, `4 / 3` for screenshots, `1` for avatars and product tiles, `21 / 9` for banners. Match the ratio to the content people expect to see. Cropping a portrait photo into a wide banner hides the subject; `object-cover` crops from the center, so add `object-top` or another position utility when faces or headlines sit near an edge.

## Accessibility [#accessibility]

Aspect Ratio adds no role and no semantics; it is layout only. The media inside still needs what it always needs: meaningful `alt` text on images, captions and a title on video, and a `title` on iframes. Use an empty `alt=""` only when the image is decorative.

Reserving space also helps people who navigate by keyboard or zoom in: focus and reading position do not jump when an image above them finishes loading. Because content is clipped, never put text that must be read in a box whose height depends on its width; at large zoom it can be cut off.

## Installation [#installation]


  

  
    <CliBlock commands="[&#x22;aspect-ratio&#x22;]" />
  

  
    
      
        Install the following dependencies:
      

      ```bash
      npm install @base-ui/react
      ```

      
        Copy and paste the following code into your project.
      

      ### components/ui/aspect-ratio.tsx

```tsx
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"

import { cn } from "@/lib/utils"

interface AspectRatioProps extends useRender.ComponentProps<"div"> {
  /** Width divided by height, such as `16 / 9`. Defaults to a square. */
  ratio?: number
}

// CSS aspect-ratio sizes the box from its width, so it needs no padding hack
// or absolutely positioned child. Overflow is clipped so media filling the
// box with object-cover keeps the rounded corners a caller adds.
function AspectRatio({
  ratio = 1,
  className,
  style,
  render,
  ...props
}: AspectRatioProps) {
  const safeRatio = Number.isFinite(ratio) && ratio > 0 ? ratio : 1

  const defaultProps = {
    "data-slot": "aspect-ratio",
    className: cn(
      "relative w-full overflow-hidden [&>img]:size-full [&>img]:object-cover [&>video]:size-full [&>video]:object-cover [&>iframe]:size-full [&>iframe]:border-0",
      className
    ),
    style: { aspectRatio: String(safeRatio), ...style },
  }

  return useRender({
    defaultTagName: "div",
    render,
    props: mergeProps<"div">(defaultProps, props),
  })
}

export { AspectRatio }
export type { AspectRatioProps }

```

      
        Update the import paths to match your project setup.
      
    
  


## Usage [#usage]

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

```tsx
<AspectRatio ratio={16 / 9} className="rounded-[var(--hui-radius-3)]">
  <img src="/cover.jpg" alt="Team at the product launch" />
</AspectRatio>
```

Use `render` to change the element, for example a `figure` or a link: `<AspectRatio ratio={1} render={<a href="/gallery/12" />}>`.

## Don't do this [#dont-do-this]

### Text that must stay readable inside a fixed ratio [#text-that-must-stay-readable-inside-a-fixed-ratio]

```tsx
// Bad
<AspectRatio ratio={16 / 9}>
  <p>Long promotional copy that wraps onto several lines…</p>
</AspectRatio>
```

When the box narrows or text zooms, the copy overflows and is clipped. Use a fixed ratio for media, and let text containers grow with their content.

## Examples [#examples]

### Common ratios [#common-ratios]

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

const ratios = [
  { label: "1:1", value: 1, use: "Avatars, product tiles" },
  { label: "4:3", value: 4 / 3, use: "Screenshots, slides" },
  { label: "16:9", value: 16 / 9, use: "Video, hero images" },
  { label: "21:9", value: 21 / 9, use: "Banners, cinematic" },
]

export function AspectRatioRatios() {
  return (
    <div className="grid w-full max-w-xl grid-cols-2 items-end gap-[var(--hui-space-4)] sm:grid-cols-4">
      {ratios.map((ratio) => (
        <div key={ratio.label} className="flex flex-col gap-[var(--hui-space-2)]">
          <AspectRatio
            ratio={ratio.value}
            className="flex items-center justify-center rounded-[var(--hui-radius-2)] border-[0.5px] border-dashed border-[var(--hui-color-border-base-tertiary)] bg-[var(--hui-color-background-base-secondary)]"
          >
            <span className="tabular-nums text-[var(--hui-color-foreground-base-primary)] [font-size:var(--hui-font-size-control,13px)] [font-weight:var(--hui-font-weight-medium)]">
              {ratio.label}
            </span>
          </AspectRatio>
          <span className="text-[var(--hui-color-foreground-base-secondary)] [font-size:var(--hui-font-size-small)] [line-height:var(--hui-line-height-small)]">
            {ratio.use}
          </span>
        </div>
      ))}
    </div>
  )
}

```

### Square gallery [#square-gallery]

Mixed portrait and landscape sources crop to the same square, so the grid rows stay even.

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

const photos = [
  { id: 12, alt: "Grayscale coastline with rocks" },
  { id: 24, alt: "Grayscale city street at dusk" },
  { id: 37, alt: "Grayscale forest path" },
  { id: 48, alt: "Grayscale mountain ridge" },
  { id: 53, alt: "Grayscale desk with a notebook" },
  { id: 66, alt: "Grayscale bridge over a river" },
]

export function AspectRatioGallery() {
  return (
    <ul className="m-0 grid w-full max-w-md list-none grid-cols-3 gap-[var(--hui-space-2)] p-0">
      {photos.map((photo) => (
        <li key={photo.id}>
          {/* Mixed source sizes crop to the same square, so rows stay even. */}
          <AspectRatio className="rounded-[var(--hui-radius-2)] bg-[var(--hui-color-background-base-secondary)]">
            <img
              src={`https://picsum.photos/400/${photo.id % 2 ? 600 : 300}?grayscale&random=${photo.id}`}
              alt={photo.alt}
              loading="lazy"
            />
          </AspectRatio>
        </li>
      ))}
    </ul>
  )
}

```

## API reference [#api-reference]

`AspectRatio` accepts all `div` props plus:

| Prop     | Values                            | Default |
| -------- | --------------------------------- | ------- |
| `ratio`  | positive number (width ÷ height)  | `1`     |
| `render` | `ReactElement` or render function | `div`   |

A ratio that is zero, negative, or not a finite number falls back to `1`. Any `style` you pass merges with the computed `aspect-ratio`, and `className` merges with the default classes.
