Decade Moon
Decade Moon

Reputation: 34286

Why does the browser not render a line break caused by a trailing newline character inside a "white-space: pre" element?

Both of these divs render the same. Why is the leading newline rendered but not the trailing newline (in the second div)? I read the Line Breaking and Word Boundaries section in the CSS3 spec but it doesn't explain this behavior.

.pre {
  white-space: pre;
  border: 1px solid red;
  margin-bottom: 10px;
}
<div class="pre">
hello
world</div>

<div class="pre">
hello
world
</div>

Upvotes: 9

Views: 1382

Answers (2)

Muran
Muran

Reputation: 82

Because the last \n won't work. And the property white-space: pre works as it's called. It only adds newline before a word. The last \n is not recognized as a word.

Upvotes: -1

Mr Lister
Mr Lister

Reputation: 46539

Why? Well, to avoid compatibility problems, apparently.

The W3C says:

In order to avoid problems with SGML line break rules and inconsistencies among extant implementations, authors should not rely on user agents to render white space immediately after a start tag or immediately before an end tag.

and also:

Note that the white space processing rules have already removed any tabs and spaces after the segment break before these checks [on the value of the white-space property] take place.

Now it is not clear exactly which inconsistencies would be introduced if the browsers were allowed to keep the whitespace before the end tag, but there you have it.

Upvotes: 6

Related Questions