Fill container by image

Use JS and CSS to center image in parent and fill parent with keeping aspect ratio

by Pavel Kutáč

HTML

<div class="imgFillContainer" style="width: 180px; height: 180px;">
    <img src="http://www.kutac.cz/image/barcode-90493.jpg" />
</div>
<a class="imgFillContainer" style="width: 290px; height: 100px;">
    <img src="http://www.kutac.cz/image/barcode-90493.jpg" />
</a>
<div class="imgFillContainer" style="width: 100px; height: 200px;">
    <img src="http://www.kutac.cz/image/barcode-90493.jpg" />
</div>

CSS

.imgFillContainer{
    border: 1px solid red;
    display: block;
    overflow: hidden;
    margin: 40px;
    position: relative;
}
.imgFillContainer .fillHeight {
    height: 100%;
    width: auto;
}
.imgFillContainer .fillWidth {
    height: auto;
    width: 100%; 
}
.imgFillContainer img {
  position: absolute;
  left: 50%;
  top: 50%;
  -ms-transform: translateY(-50%) translateX(-50%);
  -webkit-transform: translateY(-50%) translateX(-50%);
  transform: translateY(-50%) translateX(-50%);
}

JavaScript

$(function(){
  var filledImages = $(".imgFillContainer img").each(function () {
      this.onload = fillByImage; //po načtení obrázku zavoláme vyplňění
      if (this.complete || (this.naturalWidth !== "undefined" && this.naturalWidth !== 0)) {
          fillByImage.call(this); //pokud již je obrázek načten, voláme ihned
      }
  });
  
  $(window).resize(function () {
      //po změně velikosti okna opět nad všemi obrázky zavoláme vyplňovací funkci
      filledImages.each(function () {
          fillByImage.call(this);
      });
  });
});

function fillByImage() {
    //získáme obrázek a rodiče
    var t = $(this), p = t.parents(".imgFillContainer:first");
    //spočítáme poměry stran, podle kterých přiřadíme CSS třídu
    var pRatio = p.width() / p.height(), tRatio = t[0].naturalWidth / t[0].naturalHeight;
    if(pRatio < tRatio){
      t.addClass("fillHeight").removeClass("fillWidth");
    }else{
      t.addClass("fillWidth").removeClass("fillHeight");
    }
}