The problem

In a fixed width layout it is simple to specify both the width and the height of an element, but what we want in this example, is to specify the with and height of an element as percentages, that are related btween them, and not the container.

What that means ?

Lets say we want to display three images per row, and we want them to be squares.

What we want is:

width:33%;
height = width;

The simple solution for this problem, is to use padding, to force the element to keep the aspect ratio we require.

How to do this ?

  • Create a container, where we specify the width we require related to the container.
  • Create a element inside, with padding-top, wich percentage is related to the first element width.
  • Add another element inside where our content will be placed.

The html:

<div class='demo'>
  <div class='elementContainer'>
    <div class='elementScale'></div>
    <div class='elementContent'>[CONTENT HERE]</div>
  </div>
</div>

The css:

.elementContainer {
  display:inline-block;
  position:relative;
  width:33%;
  float:left;
  margin:0;
  padding:0;
}

.elementScale {
  padding-top:100%;/* AUTO ASPECT RATIO 1:1 */
  
  /*
  padding-top:75%; > ratio 4:3
  padding-top:50%; > ratio 2:1
  padding-top:33%; > ratio 3:1
  ...
  */
  
}

.elementContent {
  border:1px solid red;
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
}

View the example CSS ratio.

Download: Css and HTML example files