Autosizing images based on aspect ratio

by audetwebdesign

HTML

<div class="container">
    <h4>Portrait Style</h4>
    <img src="http://placekitten.com/240/300">
</div>
<div class="container">
    <h4>Landscape Style</h4>
    <img src="http://placekitten.com/500/300">
</div>
    
<h3 style="clear: both;">Full Size Images - For Reference</h3>
<img src="http://placekitten.com/240/300">
<img src="http://placekitten.com/500/300">

CSS

.container {
    height: 300px;
    width: 240px;
    background-color: red;
    float: left;
    overflow: hidden;
    margin: 20px;
}
.container img {
    display: block;
}
.portrait img {
    width: 100%;
}
.landscape img {
    height: 100%;
}

.container h4 {
    position: absolute;
    margin: 0;
    background-color: rgba(255,255,255,0.3);
}

JavaScript

$(".container").each(function(){
    // Uncomment the following if you need to make this dynamic
    //var refH = $(this).height();
    //var refW = $(this).width();
    //var refRatio = refW/refH;
    
    // Hard coded value...
    var refRatio = 240/300;
    
    var imgH = $(this).children("img").height();
    var imgW = $(this).children("img").width();
    
    if ( (imgW/imgH) < refRatio ) { 
        $(this).addClass("portrait");
    } else {
        $(this).addClass("landscape");
    }
})