Aspect Ratio

The React Aspect Ratio component keeps an element’s width and height in a fixed ratio. It is useful for images, videos, and embeds that need to keep the same shape across different screen sizes.

It adjusts the height based on the container width. So, the content scales correctly, and the layout does not shift during loading or resizing.

Built with React and styled using Tailwind CSS. It supports predefined aspect ratios and custom values for flexible layouts.

Video (16:9)

Installation

Install the component using the Tailgrids CLI.

npx @tailgrids/cli add aspect-ratio

Anatomy

Import the component and pass the desired aspect ratio variant or custom ratio.

import { AspectRatio } from "@/registry/core/aspect-ratio";

export const AspectRatioExample = () => (
  <AspectRatio ratio="video" className="rounded-lg overflow-hidden">
    <img
      src="path/to/image.jpg"
      alt="Description"
      className="size-full object-cover"
    />
  </AspectRatio>
);

Examples

Variants

The AspectRatio component supports eight predefined Tailwind CSS aspect ratio variants: square (1:1), video (16:9), 4/3, 3/4, 21/9, 9/16, 3/2, and 2/3.

Square (1:1)
Video (16:9)
4:3
3:4
21:9
9:16
3:2
2:3

Custom Ratio

You can specify a custom aspect ratio using the customRatio prop, which accepts any numeric value (e.g., 2.35 for cinematic widescreen).

Custom Ratio: 2.35:1 (Cinematic Widescreen)

Note: The customRatio prop takes precedence over the ratio variant when both are provided.

Images

The AspectRatio component works seamlessly with responsive images. Use object-cover or object-contain classes to control how images fill the container.

Landscape image

16:9 Landscape

Square image

1:1 Square

API Reference

AspectRatio

PropTypeDefaultDescription
ratio'square' | 'video' | '4/3' | '3/4' | '21/9' | '9/16' | '3/2' | '2/3''video'Predefined aspect ratio variant based on Tailwind CSS classes
customRationumber-Custom aspect ratio value (e.g., 16/9 | 2.35). Takes precedence over ratio
classNamestring-Additional CSS classes to apply to the container
childrenReact.ReactNode-Content to display within the aspect ratio container Required

Accessibility

  • Semantic structure: The component uses a standard <div>. Add semantic elements inside it when needed, such as <img>, <video>, or <iframe>.
  • Alt text for images: Always provide a clear alt attribute when using images so screen readers can understand the content.
  • Focus handling: The component forwards refs, so you can manage focus if the content inside is interactive.
  • Responsive behavior: The aspect ratio stays consistent across screen sizes, so content does not shift or break layout.