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);
In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.
One would then calculate the aspect ratio as a percentage to set as the padding-top . For example: 1:1 aspect ratio = 1 / 1 = 1 = padding-top: 100% 4:3 aspect ratio = 3 / 4 = 0.75 = padding-top: 75%
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With