如何在HTML5中正确使用h1

时间:2011-09-13 16:30:30

标签: html html5 seo semantics semantic-markup

以下哪一项是构建网页的正确方法:

仅在h1

1)header

<header>
    <h1>Site title</h1>
    <nav>...</nav>
</header>
<section>
    <h2>Page title</h2>
</section>

如果我在h1内专门使用header作为网站标题,则每个网页的h1标记内容都相同。这似乎没有什么信息。


对于网站和网页标题,

2)h1 headersection

<header>
    <h1>Site title</h1>
    <nav>...</nav>
</header>
<section>
    <h1>Page title</h1>
</section>

我还看到了在h1header标记中多次使用section的示例。但是,同一页面有两个标题是不是错了?此示例显示了多个标头和h1标签http://orderedlist.com/resources/html-css/structural-tags-in-html5/


3)h1仅限于section,强调网页标题

<header>
    <p>Site title</p>
    <nav>...</nav>
</header>
<section>
    <h1>Page title</h1>
</section>

最后,W3似乎建议在主h1元素中使用section,这是否意味着我不应该在header元素中使用它?

  

章节可能包含任何等级的标题,但作者强烈   鼓励要么只使用h1元素,要么使用   该部分嵌套级别的适当等级。

3 个答案:

答案 0 :(得分:57)

正如我在评论中所述,你在W3C中引用,h1是标题,而不是标题。每个切片元素都可以有自己的标题元素。您不能将h1视为页面的标题,而是将其视为页面特定部分的标题。就像报纸的头版一样,每篇文章都有自己的标题(或标题)。

Here is a good article on this.

答案 1 :(得分:13)

我建议您始终使用h1。忘记h2h6

回到HTML4中,6个标题级别用于隐式定义部分。例如,

<body>
<h1>This is a top-level heading</h1>
<p>some content here</p>
<h2>This is the heading of a subsection</h2>
<p>content in the subsection</p>
<h2>Another subsection begins here</h2>
<p>content</p>
<h1>another top-level heading</h1>

现在使用section元素,您可以显式定义这些部分,而不必依赖浏览器创建的隐式部分来读取不同的标题级别。配备HTML5的浏览器知道section元素中的所有内容都会在文档大纲中被“降级”一级。例如,section > h1在语义上被视为h2section > section > h1就像h3等。

令人困惑的是,浏览器 STILL 根据h2 - h6标题级别创建隐式部分,而h2 - h6元素不要改变他们的风格。这意味着h2,无论嵌套多少部分,仍然会显示为h2(至少在Webkit中)。如果您的h2应该是4级标题,那将会令人困惑。

h2 - h6section混合会导致非常意外的结果。只需坚持使用h1,然后使用section创建显式部分。

<body>
<!-- optional --><header>
    <h1>This is a top-level heading</h1>
    <p>you may optionally wrap this p and the h1 above it inside a header element.
     the header element doesn't affect the doc outline.
     the section element does, however.</p>
<!-- optional --></header>
<section>
    <h1>even though this is an h1, the browser "treats it" like an h2
        because it's inside an explicit section.
        (it got demoted).</h1>
    <p>content in the subsection</p>
</section>
<section>
    <h1>Another subsection begins here, also treated like an h2</h1>
    <p>content</p>
    <h2>This is misleading. it is semantically treated like an h3.</h2>
    <p>that is because after an h1, an h2 is demoted one level. the h1 above is
        already a "level 2" heading, so this h2 becomes a "level 3" heading.</p>
    <section>
        <h1>just do this instead.</h1>
        <p>it is treated like an h3 because it's in a section within a section.
            (It got demoted twice.)</p>
    </section>
</section>
<h1>another top-level heading</h1>

此外,您可以使用the <main> element。此元素仅包含特定于页面的信息,不应包含在站点范围内重复的内容,例如导航链接,站点页眉/页脚等。可能只有一个 {{1}元素存在于<main>中。所以你的解决方案可能就像这样简单:

<body>

答案 2 :(得分:4)

但是,不要忘记可访问性问题。根据{{​​3}},&#34;目前在图形浏览器或辅助技术用户代理中没有MDN的已知实现。&#34;这意味着屏幕阅读器可能无法确定仅<h1>的部分的相对重要性。它可能需要更多标题级别,例如<h2><h3>