Responsive Images Tips

When coding this site, I encountered two issues around responsive images.

The first one was a weird IE bug that would resize the images correctly in width but not in height when using height:auto and max-width:100%. After searching around for a bit, I found an easy fix, just add width:auto for it to work nicely in IE.

The second one was when setting the width (or max-width) of an element to 100% and also adding some padding. This would cause the image to expand outside the container. You can easily go around it by changing the box-sizing property to border-box.

img {
    max-width: 100%;
    height: auto;
    width: auto; /* Fix for IE */
    padding: 5px;

    /* Box Sizing */
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

If you are using Modernizr on your site, you can add a custom test to check for compatibility.

Modernizr.addTest('boxsizing', function() {
    var s = ['boxSizing', 'MozBoxSizing', 'WebkitBoxSizing', 'msBoxSizing'],
    div = document.createElement('div');

    for (var i = 0, l = s.length; i < l; i++) {
        if (div.style[s[i]] != undefined) {
            return true;
        }
    } 

    return false;
});