Maintaining Image Aspect Ratios in RWD

by Umar

HTML

<h1>Maintaining Image Aspect Ratios in RWD</h1>

<p>A series of responsive images works well if all have the same aspect ratio:</p>

<ul>
  <li><a href="#"><img src="http://lorempixel.com/320/180/abstract" /></a></li>
  <li><a href="#"><img src="http://lorempixel.com/320/180/city" /></a></li>
  <li><a href="#"><img src="http://lorempixel.com/352/198/technics" /></a></li>
</ul>

<p>But how can you set a height if images have differing sizes?</p>

<ul>
  <li><a href="#"><img src="http://lorempixel.com/320/180/abstract" /></a></li>
  <li><a href="#"><img src="http://lorempixel.com/320/320/city" /></a></li>
  <li><a href="#"><img src="http://lorempixel.com/200/150/technics" /></a></li>
</ul>

<p>We can use the top-padding percentage trick:</p>

<ul id="aspect">
  <li><a href="#"><img src="http://lorempixel.com/320/180/abstract" /></a></li>
  <li><a href="#"><img src="http://lorempixel.com/320/320/city" /></a></li>
  <li><a href="#"><img src="http://lorempixel.com/200/150/technics" /></a></li>
</ul>

<p>Please use as you wish and say "hi" to me <a href="http://twitter.com/craigbuckler">@craigbuckler</a>.</p>

<p>Refer to <a href="http://www.sitepoint.com/rwd-image-aspect-ratios/">SitePoint.com for more information&hellip;</a></p>

CSS

body
{
  font: 100% sans-serif;
  padding: 0;
  margin: 10px;
  color: #333;
  background-color: #fff;
}

ul
{
  float: left;
  width: 100%;
  padding: 0;
  margin: 0 0 2em 0;
  list-style-type: none;
}

li
{
  float: left;
  width: 33.3%;
  padding: 0;
  margin: 0;
  background-color: #000;
  border: 10px solid #fff;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

li a
{
  display: block;
  width: 100%;
  overflow: hidden;
}

img
{
  display: block;
  max-width: 100%;
  max-height: 100%;
  margin: auto;
  -webkit-transition: all 2s ease-out;
  transition: all 2s ease-out;
}

a:hover img, a:focus img
{
  -webkit-transform: scale(1.3);
  transform: scale(1.3);
}

#aspect li a
{
  position: relative;
  height: 0;
  padding-top: 56.25%;
}

#aspect img
{
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}