Browsers Trim Pixel Decimals

In all browsers but FireFox, if you have 3 equal-height divs stacked that together should equal 100px in height, you’ll end up with 99px. And if you have 30 divs stacked that together should equal 1000px, you guessed it, they’ll only reach 990px high. This is because all 33.33~px height divs will be rounded down to 33px, and the remainder is lost.

The best solution to this problem is to save and carry over the decimal point via javascript. Setting each div to be absolutely positioned might work, but is pretty heavy on the browser, and less than ideal for layout. Here’s what the code change that I’ve written looks like:

Where my code began as:

$(".oneYear li").css("height", someFraction);

My code became:

$(".oneYear li").each(function(i){
    decFix = (fixSomeFraction%1); // get the decimal value
    fixNewSmallUnitSize = parseInt(fixSomeFraction); // set fix size to an integer
    $(this).css("height", fixSomeFraction); // assign height to the fix size
    fixSomeFraction= someFraction + decFix; // add the decimal remainder to the unit size for next time
  });

First I store the remainder by dividing the fraction by one (in other words, just the stuff after the decimal). Second, I convert the number to an integer, which strips everything after the decimal. I then assign this whole number to the div’s height. And finally, I add the stored decimal value to the next div, which may or may not be bumped up by one pixel consequently.

What you see happening here is essentially just a slight modification of the loop that jQuery has to make to all the “.oneYear li” elements anyway. Although it’s easy to forget that jQuery performs this work behind the scenes, it does, and knowing that will allow you to most efficiently redefine the process for your own purposes.