Set height as a ratio of width with only css
CSS has a built-in property called aspect-ratio
just assign it to the element after height or width has been defined. CSS-tricks has an example and I made a code snippet below.
div{
width:50vw;
border: 2px solid black;
border-radius: 15px;
margin:5px;
aspect-ratio: 16/9;
}
<div>
</div>
Use viewport-width (vw
) for defining width in the height property:
width: calc(100% - 20px)
height: calc((100vw - 20px) * 0.5625) /*16:9 aspect ratio*/
The viewport
is the visible area of the web page.
Its full size is 100vw * 100vh
, where vw
and wh
are the viewports size units.
Thus one "vw
" is equal to 1%
of the web page's currently visible width.
More can be found at: Viewport units: vw, vh, vmin, vmax