shibbydoo
shibbydoo

Reputation: 569

Firefox resize image differently causing gap/extra pixels between images?

I have a row of images that floats left, I resized the images to height:160px and added the width of all the images up. Then gave the parent div a width. (In my project I'm using iScroll so that's why I'm doing this).

img {
    height: 160px;
    vertical-align: top;
    float: left;
    display:block;
}

javascript:

var scrollerWidth = 0;
$('.scroller').find('img').each(function(){
    scrollerWidth += this.width;
});

$('.scroller').css('width', scrollerWidth);

Everything works fine in Chrome and Safari, but not Firefox. In FF, the last image will go to the second row. However the total width traced out to be the same as in Chrome. And you can see there's this really tiny gap between images.(it's not always visible, if you resize the browser you can see it sometimes)

you can check my jsfiddle here http://jsfiddle.net/shibbydoo/sQGk3/10/

The reason I thought it might be due to how Firefox resize images is that if you change the height to 200px, then everything's fine. Does anyone know why is it doing this? Thanks.

ps. All the image width traced out to be the same in Chrome and FF, but it's obviously not the same...

Upvotes: 2

Views: 1292

Answers (2)

shibbydoo
shibbydoo

Reputation: 569

Thanks to compid and trojansdestroy I was able to brainstorm think of this. Since each image width is traced out to be the same in FF and Chrome (The weirdest part), I just set the width of the image to the width that's traced out, and that fixed it.

$('.scroller').find('img').each(function(){
    scrollerWidth += this.width;
    $(this).css('width', this.width);
});

Here's the jsFiddle

Upvotes: 0

compid
compid

Reputation: 1323

Cause

I believe this is due to a rounding error. When you set the height of the image to 160px and leave the width unset, you are telling the browser to set the width according to the original aspect ratio. This means the width may not be exactly an integer, but will still be rounded to the nearest integer by the browser. I suspect FFdoes the rounding slightly differently which causes an additional pixel in the total.

The most mysterious part is that both inspectors report the same widths for all the images. However, after careful inspection of a screenshot in Photoshop, it seems like Chrome renders the total image width to be 682px, while Firefox renders the total image width to be 683px (which is larger than the javascript calculated 682px).

This image: https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTYhlmIx0ZgQCMA9xmnttw4vvrZIrlZpC9QNBhN9FoBUc46DFse renders 1px wider in FF.

Fix

The best fix for this is proably to use images at 100% their size, instead of having the browser resize it. This reduces loading time to a minimum, and ensures you do not have issues with the rounding of image dimensions.

Upvotes: 4

Related Questions