渲染新行的 HTML 规范?

2024-03-23

我正在尝试将一些简单的 HTML 文档(主要包含 div 和 br 标签)呈现为纯文本,但我在何时添加新行方面遇到了困难。我以为这会很简单<div> and <br/>生成新的线条,但看起来有各种微妙的规则。例如:

<div>one line</div>
<div>two lines</div>

<hr/>

<div>one line</div>
<div></div>
<div>still two lines because the empty div doesn't count</div>

<hr/>

<div>one line<br/></div>
<div></div>
<div>still two lines because the br tag is ignored</div>

<hr/>

<div>one line<br/></div>
<div><br/></div>
<div>three lines this time because the second br tag is not ignored</div>

<hr/>

<div><div>Wrapped tags generate only one new line<br/></div></div>
<div><br/></div>
<div>three lines this time because the second br tag is not ignored</div>

因此,我正在寻找有关如何在 HTML 文档中呈现新行的规范(当未应用 CSS 时)。知道在哪里可以找到此类文档吗?


如果您正在寻找规格<div> and <br>, 您不会在一个地方找到它,因为每个地方都遵循不同的规则。 DIV 元素遵循块格式规则,而 BR 元素遵循文本流规则。

我相信您感到困惑的原因是假设它们遵循相同的换行规则。 让我解释。

BR 元素。

BR 定义于HTML4 规范第 9.3 节 https://www.w3.org/TR/html401/struct/text.html#h-9.3.2.1关于行和段落:

BR 元素强制中断(结束)当前文本行。

And in HTML5 规范第 4.5 节 https://www.w3.org/TR/html51/textlevel-semantics.html#the-br-element关于文本级语义:


元素代表换行符。

该规范解释了第三个示例的结果:

<div>one line<br/></div>
<div></div>
<div>still two lines because the br tag is ignored</div>

在那里,BR 元素根本不会被忽略,因为它标记该线必须在该点断开。 换句话说,它标记当前文本行的结尾。 这并不是要创建新线路。

在你的第四个例子中:

<div>one line<br/></div>
<div><br/></div>
<div>three lines this time because the second br tag is not ignored</div>

BR 元素也标记了该行的末尾。 由于该行有零个字符,因此它被呈现为空行。

因此,第三个和第四个示例中的规则是相同的。 没有什么是被忽略的。

DIV 元素。

如果没有明确的样式表,则应用默认样式。 DIV 元素默认是块级元素,这意味着它遵循块格式化上下文 定义于CSS 规范第 9.4.1 节 https://www.w3.org/TR/CSS22/visuren.html#block-formatting:

在块格式化上下文中,框从包含块的顶部开始垂直排列,一个接一个。

因此,这也不是创建新行,因为在块格式化上下文中,没有行的概念。 它是从上到下逐个放置块元素。

在你的第二个例子中:

<div>one line</div>
<div></div>
<div>still two lines because the empty div doesn't count</div>

空 DIV 的高度为零,因此它对下一个块级元素的渲染没有影响。

在你的第五个例子中:

<div><div>Wrapped tags generate only one new line<br/></div></div>
<div><br/></div>
<div>three lines this time because the second br tag is not ignored</div>

外部 DIV 用作包含块,如中定义的第9.1.2节 https://www.w3.org/TR/CSS22/visuren.html#containing-block内部 DIV 的定义是我上面引用的第 9.4.1 节。 因为没有应用 CSS,所以 DIV 元素默认具有零边距和零填充, 这使得内部 DIV 的每条边都与外部 DIV 的相应边接触。 换句话说,内部 DIV 的渲染位置与外部 DIV 完全相同。

我相信这就是一切。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

渲染新行的 HTML 规范? 的相关文章