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 Ratio | Width Value | Height Value |
---|---|---|
4:3 | 4 | 3 |
16:9 | 16 | 9 |
3:2 | 3 | 2 |
1:1 (square) | 1 | 1 |
2:3 | 2 | 3 |
Best Practices
- Use the
aspect-ratio
property in conjunction with thewidth
andheight
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
Chrome | Firefox | Safari | Internet Explorer | Microsoft Edge | Opera |
---|---|---|---|---|---|
Yes | Yes | Yes | No | Yes | Yes |