HTML spans and whitespace

4 Octobter 2011

Did you know that whitespace between elements is significant in HTML? I did not. Take this example:

<div>
  <span>one</span>
  <span>two</span>
  <span>three</span>
</div>

It is rendered as:

one two three

But if you remove the line breaks

<div>
  <span>one</span><span>two</span><span>three</span>
</div>

The output is:

onetwothree

Looking at the page in firebug won’t give you any clues. It reformats the HTML so both examples appear to be exactly the same. Looking at the style or layout of any of the elements will also give you no idea where the spaces are coming from. The only way to introspect what is happening is to examine one of textContent, outerHTML|Text innerHTML|Text properties of the parent element (the div in this case) which will show the line breaks and spaces.

If you are relying on the background color of your spans to make your UI look pretty (or bareable in my case), then be warned. Whitespace between spans matters.