CSS setting the height of a DIV based on a ratio of the width

I had a situation where I needed to set the height of a multiple divs to be the same, but proportionate to its width. The application had gallery like page, which each item’s width based on a percentage of the window width. Each item had an image, with a set aspect ratio and a width set to 100%. In order to get the height to scale with the window width, here’s the CSS trickery I ended up using. Of course there are Javascript methods and other CSS hacks, this was the simplest in my opinion. In the example I used images with different aspect ratios to show that the outer div’s height is not based on the image height (even though the image height is what I wanted to match so that it the item doesn’t change when the image is finished loading).

HTML

<div class="row">
   <div class="image-container"><img src="http://lorempixel.com/400/200/" /></div>
   <div class="image-container"><img src="http://lorempixel.com/400/300/" /></div>
   <div class="image-container"><img src="http://lorempixel.com/300/200/" /></div>
</div>

CSS

.row{
  display: flex;
}
.image-container{
  display: inline-block;
  position:relative;
  margin:auto;
  width: 30%;
  border:solid 1px red;
}
.image-container:after{
  content: '';
  display: block;
  margin-top: 75%;
}
.image-container img{
  position:absolute;
  top: 0;
  right:0;
  bottom:0;
  left:0;
  width:100%;
  max-height:100%;
}

Result

Here’s a jsfiddle:
https://jsfiddle.net/wyz4o4qp/

Share this:

Leave a comment