jQuery: image resizing and containing

I'm currently restyling my main website which is full of wide screenshots and images that usually are larger than 600-700 pixels (or even more). Since my new template uses a central column whose width is set in percentages, it's a little bit hard to predict in advance if those images will actually overflow the overall width of their container.

A CSS solution is to add a class to each image that is larger than the aforementioned column, like so:

img.wide {
    width: 100%;
    display: block;

This solution works fine only when the intrinsic width of the image is equal to or greater than the width of its container. But since I'm using percentages, things get more complicated. So I decided to use jQuery:

function setImageWidth() {

    if($('img').size()) {
        $('img').not('a img').each(function() {
     var $img = $(this);
     var parentWidth = $img.parent().width();
     var imgWidth = $img.width();
     if(imgWidth >= parentWidth) {
    } else {


The tricky part here concerns images inside hyperlinks. jQuery usually calculates the width of an element depending on whether if it's a block or inline element. For example, if you have a structure like this:


and the image is just a little small inline graphic (e.g. a '>' sign), then you will see the image just as big as the div element, because this ancestor is a block-level element. To use the above function, you should make sure that the link/parent that contains the image is actually a block-level element by checking if its display property is set to block. Otherwise, you can use this function as it is.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.