Layout

Aspect Ratio

Utilities for controlling the aspect ratio of an element.

Quick reference

Class
Properties
aspect-autoaspect-ratio: auto;
aspect-squareaspect-ratio: 1 / 1;
aspect-videoaspect-ratio: 16 / 9;

Basic usage

Setting the aspect ratio

Use the aspect-{ratio} utilities to set the desired aspect ratio of an element.

Aspect Ratio - 图1

  1. <iframe class="w-full aspect-video ..." src="https://www.youtube.com/..."></iframe>

Tailwind doesn’t include a large set of aspect ratio values out of the box since it’s easier to just use arbitrary values. See the arbitrary values section for more information.

Browser support

The aspect-{ratio} utilities use the native aspect-ratio CSS property, which was not supported in Safari until version 15. Until Safari 15 is popularized, Tailwind’s aspect-ratio plugin is a good alternative.


Applying conditionally

Hover, focus, and other states

Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use hover:aspect-square to only apply the aspect-square utility on hover.

  1. <iframe class="w-full aspect-video hover:aspect-square" src="https://www.youtube.com/..."></iframe>

For a complete list of all available state modifiers, check out the Hover, Focus, & Other States documentation.

Breakpoints and media queries

You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use md:aspect-square to apply the aspect-square utility at only medium screen sizes and above.

  1. <iframe class="w-full aspect-video md:aspect-square" src="https://www.youtube.com/..."></iframe>

To learn more, check out the documentation on Responsive Design, Dark Mode and other media query modifiers.


Using custom values

Customizing your theme

By default, Tailwind provides a minimal set of aspect-ratio utilities. You can customize these values by editing theme.aspectRatio or theme.extend.aspectRatio in your tailwind.config.js file.

tailwind.config.js

  1. module.exports = {
  2. theme: {
  3. extend: {
  4. aspectRatio: {
  5. '4/3': '4 / 3',
  6. },
  7. }
  8. }
  9. }

Learn more about customizing the default theme in the theme customization documentation.

Arbitrary values

If you need to use a one-off aspect-ratio value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value.

  1. <iframe class="w-full aspect-[4/3]" src="https://www.youtube.com/..."></iframe>

Learn more about arbitrary value support in the arbitrary values documentation.