为什么浏览器将换行显示为空格?

很长一段时间以来,我一直想知道为什么浏览器在呈现的 HTML 元素之间添加一个空白空间,而它们之间有一个 NewLine,例如:

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

上面的 html 将在“ Hello”和“ World”之间输出“ HelloWorld”字符串 没有,但是在下面的示例中:

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

上面的 html 将在“ Hello”和“ World”之间输出一个“ Hello World”字符串

现在,我可以毫不犹豫地接受这种工作方式,但有一点让我感到困扰的是,我一直以为在浏览器向用户呈现 html 时,html 元素之间的空格(或换行符)并不重要。

所以我的问题是,是否有人知道这种行为背后的哲学或技术原因。

谢谢你。

35874 次浏览

Browsers condense multiple whitespace characters (including newlines) to a single space when rendering. The only exception is within <pre> elements or those that have the CSS property white-space set to pre or pre-wrap set. (Or in XHTML, the xml:space="preserve" attribute.)

If you had the character 'a' between two tags, you would expect it to get rendered. In this case, you have a character '\n' between two tags; the behaviour is analogous, and consistent ('\n' is rendered as a single whitespace).

HTML is specified to do it like that:

Line breaks are also white space characters

http://www.w3.org/TR/REC-html40/struct/text.html#h-9.1

Whitespace between block elements are ignored. However, whitespaces between inline elements are transformed into one space. The reasoning is that inline elements might be interspersed with regular inner text of the parent element.

Consider the following example:

<p>This is my colored <span class="red_text">Hello</span> <span class="blue_text">World</span> example</p>

In the ideal case, you want the user to see

This is my colored Hello World example

Removing the whitespace between the two spans however would result in:

This is my colored HelloWorld example

But that same sample can be rewritten by an author (with OCD about the HTML formatting :-)) as:

<p>
This is my colored
<span class="red_text">Hello</span>
<span class="blue_text">World</span>
example
</p>

It would be better if this was rendered consistently with the previous example.

Browsers make a mistake here:

http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.1

SGML (see [ISO8879], section 7.6.1) specifies that a line break immediately following a start tag must be ignored, as must a line break immediately before an end tag. This applies to all HTML elements without exception.

you can use the html comment tag to connect the code to avoid the space.

<p>
This is my
<span class="red_text">Hello</span><!--
--><span class="blue_text">World</span>
example
</p>