Mike Hartman Mike Hartman - 7 months ago 9
HTML Question

CSS % widths not adding up to 100%, discrepancy seems to scale with font size

Does anyone have any idea why two blocks with 48% widths and 4% total horizontal margins wouldn't fit onto the same line without wrapping? Something simple like:

<div style="width: 500px; margin: 0; padding: 0;">
<div style="width: 48%; margin: 0 0 0 2%; padding: 0; background-color: red; display: inline-block;">A</div>
<div style="width: 48%; margin: 0 0 0 2%; padding: 0; background-color: red; display: inline-block;">B</div>
</div>


jsFiddle

It's been driving me crazy, and it happens across Firefox, Chrome and IE8. Windows and Linux.

At my standard zoom setting I can get them on the same line using "width: 47.5%". And I could live with that if it was consistent, but at my minimum zoom it needs to be 47.8% and at my maximum zoom it needs to be 46.5%. So I can't get a consistent whitespace alignment with other elements on my page across all zooms.

I initially assumed it was just a rounding error, but since the fudge factor seems to be dependent on font size there's got to be more to it. I can probably find some way to make my page look ok anyway, but I really want to know why it's doing this. It's going to keep me up tonight.

Answer

Its the white spaces between the divs that are making up the extra space. Since these divs are inline-block the white spaces around them are rendered

<div class="should_fit">A</div><div class="should_fit">B</div>

http://jsfiddle.net/cMHgE/4/