HTML: 文本是否需要符合标准的容器元素?

HTML: Does text need a container element conform to standards?

以下是否符合 W3C 标准:

<div>
  <h3>Heading</h3>
  This is the text for this section.
</div>

或者文本是否需要容器元素?

<div>
  <h3>Heading</h3>
  <p>This is the text for this section.</p>
</div>

第一个例子不适合我,但一位内容编辑问了我,我意识到我真的不知道它是否合适。

两个例子都有效。

从技术上讲,在第一个中,文本 是容器内的 ,外部 <div>.

无论如何,将文本直接放在 <body>, which means the following HTML document will pass validation 中是完全有效的,没有错误或警告:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
    <h3>Heading</h3>
    This is the text for this section.
</body>
</html>

更相关的问题是是否semantically correct。简而言之,段落文本应该被 <p> 标记包围。更一般地说,每种类型的内容都应该写在语义相关的标签内。

我会建议你使用第二种方法。 当您使用正确的标题标签时,它有助于明智地提升您的页面 SEO。 此外,段落标签 P 可帮助某些浏览器以“阅读模式”呈现您的页面。 最后,div 是一个 block-displayed 元素。这个 CSS 代码看起来有点奇怪:div {color: blue}。但是,p { color: red; } 对很多人来说更有意义。

从技术上讲,两者都符合 HTML(除非您根据严格的 HTML4.x/XHTML1.x 方案对其进行验证,其中 has no connection to reality anymore). Hovewer, the second approach would be probably more convenient from the styling/scripting perspective, where it's always better to have a possibility to address any piece of content directly. The first example has an implicit paragraph 和显式通常更好比隐式。