Alexander Alexander - 1 year ago 191
CSS Question

Set height as a ratio of width with only css

I want to achieve the following for an

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
elements and their background. But in the case of
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);

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download