Search code examples
htmlcssimagesize

Set height as a ratio of width with only css


I want to achieve the following for an <img> element in HTML, using only CSS:

width: calc(100% - 20px)
height: calc(width * 0.5625) /*16:9 aspect ratio*/

There are similair examples all over the internet regarding <div> elements and their background. But in the case of <img> elements, changing the padding does not work

Similair example: Maintain the aspect ratio of a div with CSS

Edit, using jQuery one can achieve the above with:

$(".myImage/s").outerHeight($(".myImage/s").outerWidth() * 0.5625);

Solution

  • 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