Aspect Ratio

The Aspect Ratio component helps you maintain a consistent aspect ratio for content, particularly useful for responsive images, videos, and embedded content. It ensures that content maintains desired proportions across different screen sizes.

This component is built with React and styled using Tailwind CSS, offering predefined aspect ratio variants as well as support for custom ratios.

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 HTML: The component uses a standard <div> element that can be enhanced with ARIA attributes as needed.
  • Image Alt Text: When using images, always provide descriptive alt text for screen readers.
  • Focus Management: The component forwards refs, allowing you to manage focus programmatically when needed.
  • Responsive Design: Aspect ratios are maintained across all screen sizes, ensuring consistent presentation for all users.