Responsive Images Inside Container

by Louis Walch

HTML

<div class="container">
  <p>Exact</p>
  <img src="http://dummyimage.com/600x400/000/fff"/>
</div>

<div class="container">
  <p>Fit to width</p>
  <img src="http://dummyimage.com/600x200/000/fff"/>
</div>

<div class="container">
  <p>Fit to height</p>
  <img src="http://dummyimage.com/200x600/000/fff"/>
</div>

CSS

.container {
  background-color: pink;
  margin-bottom: 20px;
  height: 0;
  padding-top: 66.6%; /* (H/W) * 100 */
  overflow: hidden;
  position: relative;
}
.container IMG {
  position: absolute;
  top: 0;
  left: 0;
  display: block;
  width: 100%;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}
.container P {
  z-index: 2;
  color: white;
  position: absolute;
  top: 10px;
  left: 10px;
  font-family: sans-serif;
  font-size: 11px;
  font-weight: bold;
  text-transform: uppercase;
  letter-spacing: 0.8px;
}