Best method now : the aspect-ratio
property
div {
aspect-ratio : 1 / 1;
width:50%;
border:1px solid red;
}
<div>Aspect ratio : 1 / 1</div>
This is the most simple and flexible solution. It directly specifies a fixed width to height (or height to width) aspect ratio for an element. This means you can also specify an aspect ratio according to the elements height.
It doesn t rely on the parent width (like the padding technique) or the viewport size (like the following vw
unit technique) it relies on the element s own width or height More info on MDN. That is what make it so powerfull compared to other workarounds.
This is a modern property (2021). All modern browsers support it, see caniuse for precise browser support.
Other method with vw
:
You can use vw
units for a responsive height/width according to the viewport width.
vw : 1/100th of the width of the viewport. (Source MDN)
You can also look into vh
, vmin
and vmax
units to se apsect ratio according to other viewport sizes (see here)
div{
width:20vw;
height:60vw; /* <-- 3 x width */
background:gold;
}
div > div{
width:15vw;
height:15vw; /* <-- same as width */
background:red;
}
<div>
1:3 aspect ratio
<div>1:1 aspect ratio</div>
</div>
Table to calculate height according to the desired aspect ratio and width of element.
aspect ratio | multiply width by
-----------------------------------
1:1 | 1
1:3 | 3
4:3 | 0.75
16:9 | 0.5625
This technique allows you to :
- insert any content inside the element without using
position:absolute;
- no unecessary HTML markup (only one element)
- adapt the elements aspect ratio according to the height of the viewport using vh units
- you can make a responsive square or other aspect ratio that alway fits in viewport according to the height and width of the viewport (see this answer : Responsive square according to width and height of viewport or this demo)
These units are supported by IE9+ see canIuse for more info