1. css
  2. /properties
  3. /aspect-ratio

aspect-ratio

Definition

The aspect-ratio property in CSS is used to specify the ratio of width to height for a container element. It is used to preserve the aspect ratio of an element's content, such as an image or video, as the element is resized.

Examples

Preserving the aspect ratio of a video element:

.video-container {
  aspect-ratio: 16/9;
}

video {
  width: 100%;
  height: auto;
}

Preserving the aspect ratio of an image with a fixed width:

.image-container {
  aspect-ratio: 4/3;
  width: 800px;
}

img {
  width: 100%;
  height: auto;
}

Preserving the aspect ratio of an image with a fixed height:

.image-container {
  aspect-ratio: 4/3;
  height: 600px;
}

img {
  width: auto;
  height: 100%;
}

Values

The aspect-ratio property takes two values: a width value and a height value. These values define the ratio of width to height for the element. Here is a table of common aspect ratios and their corresponding width and height values, formatted in Markdown and presented in a copyable code block:

Aspect RatioWidth ValueHeight Value
4:343
16:9169
3:232
1:1 (square)11
2:323

Best Practices

  • Use the aspect-ratio property in conjunction with the width and height properties to specify the size of the container element.
  • Avoid using the aspect-ratio property on elements that do not contain media, such as text or other elements.
  • Consider the size and layout of the page when choosing an aspect ratio for the element.
  • Use the aspect-ratio property in combination with media queries to create responsive layouts that adapt to different screen sizes and resolutions.

Browser Compatibility

ChromeFirefoxSafariInternet ExplorerMicrosoft EdgeOpera
YesYesYesNoYesYes