Why the background of <span> behaves differently when the content contains new lines?

css, html

Solution

EDIT: For addressing the particular issue which inspired this question, using a style of

span {
  display: inline-block;
}

will allow both forms of your HTML to yield the white sliver in between the 2 red blocks, since now the spans have block spacing and sizing while still adhering to an inline positioning. Anyway, onto the explanation:

Newline or a space are both a single white space. If 2 inline elements have a single space between them, you get that little sliver of white space.

<span>Hello</span>
<span>World</span>

has a single space (the newline) between the 2 span elements. It is equiavelent to this

<span>Hello</span> <span>World</span>

However,

<span>Hello </span>
<span>World</span>

has no space between the span elements, because its HTML so any amount of contiguous white space is considered a single whitespace. this time, the first whitespace is inside of the span, so it gets a red background, the second white space (the newline) gets bunched up with the first one, which has a red background already, so no white sliver is seen. The above block is equivalent to your

<span>
  Hello
</span>
<span>
  World
</span>

because the whitespace after the "o" is inside the span, so that gets bunched up with the newline whitespace outside the span, as well as the newline whitespace inside the second span before the W, so the background is contiguous.

You can see that

<span>Hello</span><span>World</span>

would have a contiguous red background also, but with no visible spacing between the words.

Problem

To demonstrate the behaviour with some visual feedback we have the following style for the `span`: ``` span { background-color: red; } ``` If we write something like this, then the result looks OK and both spans have red background with a space in between: ``` <span>Hello</span> <span>World</span> ``` But when we change the HTML to something like this, then there is no space between the two spans: ``` <span> Hello </span> <span> World </span> ``` I would assume that the spaces and new lines wouldn't affect anything. So my question is why is that happening and what am I missing here? Here is a screenshot of the first and second behaviour in action (tested on Chrome, Safari, Firefox): jsbin.com/eGElekoW

Original source