<div class="container" style="--width: 600px">
  <div class="intro">
    <h1>Aspect Ratio Images</h1>
    <p>Combining the padding "hack" with css variables, we can make a wrapper for any image, to display at a certain size. All with CSS, no javascript involved.</p>
    <p>To make as reusable as possible, we're passing through through the required aspect ratio inline eg. <code>style="--aspect-ratio: 16/9"</code> which sets the padding-top using calc. The image inside the wrapper, is then set to fill the div using object-fit. In this demo it is set to user cover, but you could use a different fill option <i>(fill, contain, cover, none, scale-down)</i>.</p>
    <p>All images are supplier square to showcase the aspect ratio in effect</p>
  </div>

  <h2>16/9</h2>
  <div class="aspectratio" style="--aspect-ratio: 16/9"><img src="//placehold.it/400x400" alt=""></div>
  <h2>21/9</h2>
  <div class="aspectratio" style="--aspect-ratio: 21/9"><img src="//placehold.it/400x400" alt=""></div>
  <h2>4/3</h2>
  <div class="aspectratio" style="--aspect-ratio: 4/3"><img src="//placehold.it/400x400" alt=""></div>
  <h2>9/16</h2>
  <div class="aspectratio" style="--aspect-ratio: 9/16"><img src="//placehold.it/400x400" alt=""></div>

</div>
//  ---------------
//  Requied CSS
//  ---------------


.aspectratio {
  position: relative;
  height: 0;
  width: 100%;
  padding-top: calc(100% / (var(--aspect-ratio)));
  
  img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}





//  ---------------
//  Only for codepen styling
//  ---------------

.container {
  margin: 50px auto;
  max-width: var(--width);
}

.intro {
  margin-bottom: 40px;
  
  code {
    background: #011627;
    color: #ABB6C4;
    padding: 2px 4px;
    border-radius: 2px;
    font-size: 14px;
  }
  
  h1 {
    color: #333;
  }
  
  p {
    font-size: 14px;
    line-height: 1.4;
    color: #555;
  }
}

h2 {
  margin-top: 32px;
}
View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.