Html – Browser white space rendering

htmlwhitespace

Recently I was editing someone else's code and I noticed that spaces were used something like the following:

<div>Some text &nbsp; &nbsp; &nbsp; Some other text</div>

I naturally assumed that the browser would combine the extra spaces, so this is really just four spaces. Testing this out though – it is actually 7 spaces (in chrome at least)! This is because the browser renders both the in between spaces and the nbsp; spaces as well.

So my question is, when will the browser render white space and when won't it? In other words, when will a single space character be rendered vs ignored?

JSFiddle Demo: http://jsfiddle.net/L7x7t/3/

Best Answer

Browsers only collapse consecutive regular space characters. Text rendering is mostly governed by the CSS spec rather than the HTML spec (with exceptions); with respect to whitespace collapsing, section 16.6.1 of CSS2.1 has the details. Specifically:

any space (U+0020) following another space (U+0020) — even a space before the inline, if that space also has 'white-space' set to 'normal', 'nowrap' or 'pre-line' — is removed.

Since there's a non-breaking space separating every two space characters that would otherwise be consecutive (and non-breaking spaces are not considered "regular" space characters), the browser has no opportunity to collapse any of them, and so must render all of them in sequence.

The behavior across browsers is mostly identical, except for a nasty bug in Chrome regarding the part about "a space before the inline".