How web browsers handle rounding when it comes to values set in percentage

Ever had the problems with width set in percentage, and every web browser seem to treat it differently? Elements falling down in IE, ruining your layout? I sure have, and John Resig explains how it really works.

In Sub-Pixel Problems in CSS he compares how IE 6, IE 7, Firefox, Opera and Safari treat the width of elements, when the value in percentage won’t match a whole pixel. The example is a containing element with a width of 50 pixels, and 4 child elements where each has a respective width of 25%.

This means that each child would get 25% width out of 50 pixels, i.e. 12.5 pixels. Since that’s not technically possible, each web browser handles this in its own way:

  • IE rounds up to 13 pixels for each element, resulting in that the collected width of all children elements exceed that of its parent, and the last element will fall down to the next row. A very poor way to do it, in my opinion.
  • Safari and Opera rounds down to 12 pixels, making sure that all elements fin in the same row, but won’t fill the entire width. Better, but still not optimal.
  • Firefox objective is to fill the entire row, while at the same time make sure nothing falls down to the next row. To achieve this, it rounds some elements to 12 pixels width and others to 13 pixels. Given the scenario, this seems like the best way to. Besides, pixel-perfection is usually a vain struggle anyway.

Make sure to read Sub-Pixel Problems in CSS for a full explanation, and images showing off the results.

7 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *