CSS trick to create square elements based on container's width

So you have some kind of responsive CSS grid in place, let's say Bootstrap's, and you need to create inner elements with same height as container width.
Something like this:

<div class="row">
  <div class="col-sm-3">
    <!-- Element with same height as parent's width -->
  </div>
</div>

I've had this problem few years ago, and Marko Dumić
helped me with pure CSS solution. Since then I copy/paste this snippet to various projects.

// Usage example:
// div.col-sm-3
//   div.square-size-by-width
//     div.square-size-element
//       img
.square-size-by-width {
  position: relative;
  width: 100%;
  padding-bottom: 100%;

  .square-size-element {
    position: absolute;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
}

Here is HTML markup from teaser with inner markup:

<div class="row">
  <div class="col-sm-3">
    <div class="square-size-by-width">
	    <div class="square-size-element">
	    </div
    </div
  </div>
</div>

This ensures elements inside your grid will scale with grid and maintain proportions!

Show Comments