Just create a wrapper <div>
with a percentage value for padding-bottom
, like this:
.demoWrapper {
padding: 10px;
background: white;
box-sizing: border-box;
resize: horizontal;
border: 1px dashed;
overflow: auto;
max-width: 100%;
height: calc(100vh - 16px);
}
div {
width: 100%;
padding-bottom: 75%;
background: gold; /** <-- For the demo **/
}
<div class="demoWrapper">
<div></div>
</div>
It will result in a <div>
with height equal to 75% of the width of its container (a 4:3 aspect ratio).
This relies on the fact that for padding :
The percentage is calculated with respect to the width of the generated box's containing block [...] (source: w3.org, emphasis mine)
Padding-bottom values for other aspect ratios and 100% width :
aspect ratio | padding-bottom value
--------------|----------------------
16:9 | 56.25%
4:3 | 75%
3:2 | 66.66%
8:5 | 62.5%
Placing content in the div :
In order to keep the aspect ratio of the div and prevent its content from stretching it, you need to add an absolutely positioned child and stretch it to the edges of the wrapper with:
div.stretchy-wrapper {
position: relative;
}
div.stretchy-wrapper > div {
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
}
Here's a demo and another more in depth demo
I did find an answer to this. It adds a little bit of unsemantic markup, but works well.
Can find it here: http://jsfiddle.net/AdQ3P/
The logic is in the padding-bottom. basically this needs to be (img_height / img_width) * 100.
Edit Here's the code, so not dependent on jsfiddle.
<div class="container">
<div class="hero"></div>
</div>
.container {
width:100%;
max-width:500px;
}
.hero {
width:100%;
height:0;
background-size:100%;
background:url(http://img97.imageshack.us/img97/3410/photo2ue.jpg) no-repeat;
padding-bottom:75%;
}
Also that was one messy desk i had lol.
Best Answer
The aspect-ratio property (2022)
To maintain the aspect ratio of a
div
according to width and height, you can use theaspect-ratio
property (MDN reference).This allows you to maintain any aspect ratio according to the viewport size or to the size of the parent element.
Maintaining aspect-ratio according to the viewport size (width and height) :
Maintaining aspect ratyio according to the parent elements size (width and height) :
Previous answer with vmin units
This still works fine but it doesn't allow to maintain the aspect ratio according to a parent element size.
To maintain the aspect ratio of a div according to width and height in the viewport, you can use one HTML tag with:
position: absolute
andmargin: auto;
for the centeringDEMO (resize both window height and width to see it in action)
Features :
Browser support :
vmin
units are supported by IE10+ (canIuse) for IE9 support, you need to use a fallback withvm
units instead ofvmin
like this :Full code: