Stretching images

by Terry Mun

HTML

<div>
    <img src="http://placehold.it/500x350" />
</div>
<div>
    <img src="http://placehold.it/350x500" />
</div>
<div>
    <img src="http://placehold.it/500x500" />
</div>

CSS

div {
    background-color: #999;
    border: 1px solid #333;
    float: left;
    margin: 10px;
    width: 100px;
    height: 300px;
}

JavaScript

$(document).ready(function() {
    $("img").each(function() {
        // Calculate aspect ratio and store it in HTML data- attribute
        var aspectRatio = $(this).width()/$(this).height();
        $(this).data("aspect-ratio", aspectRatio);

        // Conditional statement
        if(aspectRatio > 1) {
            // Image is landscape
            $(this).css({
                width: "100%",
                height: "auto"
            });
        } else if (aspectRatio < 1) {
            // Image is portrait
            $(this).css({
                maxWidth: "100%"
            });
        } else {
            // Image is square
            $(this).css({
                maxWidth: "100%",
                height: "auto"
            });            
        }
    });
});