Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set height as a ratio of width with only css

Tags:

html

css

image

size

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);
like image 399
Alexander Avatar asked Oct 15 '16 17:10

Alexander


People also ask

How do you make a 16 9 ratio in CSS?

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.

How do you define aspect ratio in CSS?

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%


2 Answers

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>
like image 172
SamsonTheBrave Avatar answered Oct 16 '22 00:10

SamsonTheBrave


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

like image 43
HelpingHand Avatar answered Oct 16 '22 00:10

HelpingHand