Search code examples
htmlcssaspect-ratio

Container padding image aspect ratio


I'm trying to do a common trick, but I'm clearly doing something wrong as I'm not having the desired outcome. I'm trying to fill a container with padding using an image's aspect ratio, so it should make the container the same height as the image.

I read online that to get an image's ratio you have to do:

height / width * 100

HTML

<div class="box">
  <img src="..." width="100" height="150" />
</div>

CSS

.box {
  padding-bottom: 150%;
  position: relative;
  background: red;
  width: 100px;
}

.box img {
  position: absolute;
  max-width: 100%;
  opacity: 0.8;
  height: auto;
  width: 100%;
  left: 0;
  top: 0;
}

Here's a fiddle showing what I've done.

Anyone know what I'm doing wrong here?


Solution

  • you need a container for your box as the padding-bottom:150% is 150% of the parent element:

    .container {
      width: 100%;
      max-width: 100px;
    }
    
    .box {
      padding-bottom: 150%;
      position: relative;
      background: red;
      width: 100%;
    }
    
    .box img {
      position: absolute;
      max-width: 100%;
      opacity: 0.8;
      height: auto;
      width: 100%;
      left: 0;
      top: 0;
    }
    <div class="container">
      <div class="box">
        <img src="https://placeholdit.imgix.net/~text?txtsize=20&txt=100%C3%97150&w=100&h=150" />
      </div>
    </div>