Skip to content

Aspect Ratio

Keep media at a fixed aspect ratio and reserve its space before it loads.

import { AspectRatio } from '@youj/react'

Installation & usage

npm i @youj/react

For an app already set up with npx @youj/cli init, which installs the peers (@youj/core, @youj/motion, motion and Base UI) and wires the provider. New app? Start at Installation.

Use an aspect ratio around images, video, embeds and their placeholders in fluid layouts. The box reserves its height from its width before the media arrives, so nothing below it jumps when it does.

import { AspectRatio } from '@youj/react'

export function Thumbnail() {
  return (
    <AspectRatio ratio={16 / 9} className="overflow-hidden rounded-lg">
      <img src="/keynote.jpg" alt="The keynote stage" className="size-full object-cover" />
    </AspectRatio>
  )
}

ratio is width over height as a number: 16 / 9, 1, 4 / 5. It's the CSS aspect-ratio property, so it needs no JavaScript and renders the same on the server. Give the child size-full (and object-cover for media) to fill the box. The API matches shadcn/ui's Aspect Ratio.

Reference

Propsratio (1)

Props

AspectRatio props
PropType
ratioRequirednumber

Width over height, as a number: 16 / 9, 1, 4 / 5.

–
Reduced motionAspect Ratio is static

Reduced motion

Aspect Ratio is static. Nothing changes under reduced motion.

AccessibilityARIA

Accessibility

  • The box is a plain div with no role. Give the media inside it its own text alternative: alt on an image, a title on an iframe.