<h2>Maintain Aspect Ratio #3</h2>
    <p>Resize the window to see the effect.</p>


    
    <div class="demo">
        <div class="grid">
          
            <div class="wrapper padded-container">
                <img class="img centered" src="http://via.placeholder.com/330x344">
            </div>
          
            <div class="wrapper padded-container">
                <img class="img centered" src="http://via.placeholder.com/816x481">
            </div>
          
            <div class="wrapper padded-container">
                <img class="img centered" src="http://via.placeholder.com/604x611">
            </div>
          
            <div class="wrapper padded-container">
                <img class="img centered" src="http://via.placeholder.com/940x667">
            </div>
          
        </div>
    </div>
$ratio-16-9: 56.25%;
$cols: 4;

.grid {
  display: flex;
  flex-wrap: wrap;
}

.wrapper {
  width: calc(100% / #{$cols});
  margin: 2px;
  border: 1px solid red;
}


.padded-container {
  height: 0;
  position: relative;
  overflow: hidden;
  padding-bottom: #{$ratio-16-9 / $cols};
}

.img {
  width: 100%;
  height: auto;
}

.centered {
  position: absolute;
  top: -50%;
  left: -50%;
  right: -50%;
  bottom: -50%;
  margin: auto;
}
View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.