为什么 HTML 要求多个空格在浏览器中显示为单个空格?

2022-01-12 00:00:00 whitespace formatting html

我早就认识到 HTML 文件中的任何一组空格都只会显示为一个空格.例如,这个:

I have long recognized that any set of whitespace in an HTML file will only be displayed as a single space. For instance, this:

<p>Hello.        Hello. Hello. Hello.                       Hello.</p>

显示为:

你好.你好.你好.你好.你好.

Hello. Hello. Hello. Hello. Hello.

这很好,好像您需要多个预先格式化的文本空格,您可以使用 <pre>标签.但原因是什么?更准确地说,为什么在 HTML 规范中会出现这种情况?

This is perfectly fine, as if you need multiple spaces of pre-formatted text you can just use the <pre> tag. But what is the reason? More precisely, why is this in the specification for HTML?

推荐答案

HTML 中的空格是压缩的,因为 HTML 的格式化方式和呈现方式之间存在区别.考虑这样一个页面:

Spaces are compacted in HTML because there's a distinction between how HTML is formatted and how it should be rendered. Consider a page like this:

<html>
    <body>
        <a href="mylink">A link</a>
    </body>
</html>

例如,如果 HTML 使用空格缩进,则链接前面会带有多个空格.

If the HTML was indented using spaces for example, the link would be preceded by several spaces.

相关文章