Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
220 views
Welcome To Ask or Share your Answers For Others

1 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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...