Force-fit image to fit viewport

by audetwebdesign

HTML

<div class="container">
    <img src="http://placehold.it/1600x1200" />
</div>

CSS

html, body {
    height: 100%;
    margin: 0;
}
.container {
    height: 100%;
    width: 100%;
    background-color: red;
    text-align: center; /* optional */
}
.container img {
    vertical-align: top;
}
.portrait img {
    width: 100%;
}
.landscape img {
    height: 100%;
}

JavaScript

function resizeImg() {
    var thisImg= $('.container');
    var refH = thisImg.height();
    var refW = thisImg.width();
    var refRatio = refW/refH;
    
    var imgH = thisImg.children("img").height();
    var imgW = thisImg.children("img").width();
    
    if ( (imgW/imgH) > refRatio ) { 
        thisImg.addClass("portrait");
        thisImg.removeClass("landscape");
    } else {
        thisImg.addClass("landscape");
        thisImg.removeClass("portrait");
    }
}

$(document).ready(resizeImg())

$(window).resize(function(){
    resizeImg();
});