为什么 <p>标签包含一个 <div>标签里面呢?

2022-01-30 00:00:00 html xhtml

据我所知,这是对的:

<p>一些话</p></div>

但这是错误的:

<p><div>一些词</div></p>

第一个可以通过W3C 验证器 (XHTML 1.0),但第二个不能.我知道没有人会像第二个那样编写代码.我只是想知道为什么.

那么其他标签的包含关系呢?

解决方案

查找允许的包含关系的权威位置是 HTML 规范.例如,参见 http://www.w3.org/TR/html4/sgml/dtd.html.它指定哪些元素是块元素,哪些是内联元素.对于这些列表,请搜索标记为HTML 内容模型"的部分.

对于P元素,指定如下,表示P元素只允许包含内联元素.

这与 http://www.w3.org/TR/html401/struct/text.html#h-9.3.1,其中表示 P 元素不能包含块级元素(包括 P 本身)."

As far as I know, this is right:

<div>
  <p>some words</p>
</div>

But this is wrong:

<p>
  <div>some words</div>
</p>

The first one can pass the W3C validator (XHTML 1.0), but the second can't. I know that nobody will write code like the second one. I just want know why.

And what about other tags' containment relationship?

解决方案

An authoritative place to look for allowed containment relations is the HTML spec. See, for example, http://www.w3.org/TR/html4/sgml/dtd.html. It specifies which elements are block elements and which are inline. For those lists, search for the section marked "HTML content models".

For the P element, it specifies the following, which indicates that P elements are only allowed to contain inline elements.

<!ELEMENT P - O (%inline;)*            -- paragraph -->

This is consistent with http://www.w3.org/TR/html401/struct/text.html#h-9.3.1, which says that the P element "cannot contain block-level elements (including P itself)."

相关文章