aspect-ratio
Sets the ratio of an element’s width to its height.
- Initial value
auto- Inherited
- No
- Applies to
- all elements except non-replaced inline elements and internal table elements
- JavaScript
element.style.aspectRatio = "16 / 9"
Example
#.thumbnail {
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
border-radius: 12px;
}<img class="thumbnail" src="/collections/covers/gry-do-nauki-programowania.webp" alt="" style="max-width: 360px; display: block;">Definition and usage
#The aspect-ratio property gives an element a fixed ratio, for example 16 / 9 for a video or 1 / 1 for a square avatar. Set just one dimension, and the browser works out the other for you.
Before this property reached browsers, aspect ratios were faked with a percentage-padding trick. Today, one readable line does the job.
If you set both dimensions explicitly, aspect-ratio is ignored. Content that doesn’t fit the calculated height can also push the element taller, unless you add an overflow other than visible or min-height: 0.
Syntax
#aspect-ratio: auto | <width> / <height>;Values
#Values in practice
#auto
.demo { aspect-ratio: auto; }1 / 1
.demo { aspect-ratio: 1 / 1; }16 / 9
.demo { aspect-ratio: 16 / 9; }3 / 4
.demo { aspect-ratio: 3 / 4; }Browser support
#Widely available · since 2021
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Combine
aspect-ratiowithobject-fit: coverso images with different proportions look uniform in a grid. - Set the aspect ratio for a video or ad slot up front, and the page won’t jump while it loads.
Related entries
#Spotted a mistake or missing an example? Write to us.