在这篇文章中,我将给大家分享html5构建页面的小错误和不好的实践方法,让我们在以后的工作中避免这些错误。
不要把 <Section> 当成简单的容器来定义样式我们经常看到的一个错误,就是武断的将<div>标签用<section>标签来替代,特别是将作为包围容器的<div>用<section>来替换。在XHTML或者HTML4中,我们将会看到类似下面的代码:
01 <!-- HTML 4-style code -->
02 <div id="wrapper">
03 <div id="header">
04 <h1>My super duper page</h1>
05 <!-- Header content -->
06 </div>
07 <div id="main">
08 <!-- Page content -->
09 </div>
10 <div id="secondary">
11 <!-- Secondary content -->
12 </div>
13 <div id="footer">
14 <!-- Footer content -->
15 </div>
16 </div>
现在我看到了下面的代码样子:
01 <!-- Don’t copy this code! It’s wrong! -->
02 <section id="wrapper">
03 <header>
04 <h1>My super duper page</h1>
05 <!-- Header content -->
06 </header>
07 <section id="main">
08 <!-- Page content -->
09 </section>
10 <section id="secondary">
11 <!-- Secondary content -->
12 </section>
13 <footer>
14 <!-- Footer content -->
15 </footer>
16 </section>
直观的看,上面的例子是错误的:<section> 并不是一个容器.<section>元素是有语意的区段,帮助构建文档大纲。它应该包含标题。如果你要寻找一个可以包含页面的元素(不论是 HTML 或者 XHTML ),通常的做法是直接对<body>标签定义样式就像Kroc Camen描述的那样子,如果你还需要额外的元素来定义样式,使用<div>,就像Dr Mike 阐述的那样, div并没有灭亡,如果这里没有其它更合适的,div可能是你最合适的选择。
记住这点,这里我们重新修正了上面的例子,通过使用两个新角色。(你是否需要额外的<div>取决于你的设计。)
01 <body>
02 <header>
03 <h1>My super duper page</h1>
04 <!-- Header content -->
05 </header>
06 <div role="main">
07 <!-- Page content -->
08 </div>
09 <aside role="complementary">
10 <!-- Secondary content -->
11 </aside>
12 <footer>
13 <!-- Footer content -->
14 </footer>
15 </body>
如果你还是无法确定哪一个元素更适合使用,我建议你去查看HTML5 sectioning content element flowchart来让你继续前行。
只在需要的时候使用 <hgroup>和<header>标签使用标记的时候写入了一些并不需要的现象这是不合理的。不幸的是,经常发现大家在并不需要的地方使用<header>和<hgroup>标签。你可以跟进我们关于<header>和<hgroup>的最新进展,下面是我的简单归纳:
你肯定知道,在一个文档中,可以使用多次<header>标签,下面就是一种很受大家欢迎的模式:
1 <!-- Don’t copy this code! No need for header here -->
2 <article>
3 <header>
4 <h1>My best blog post</h1>
5 </header>
6 <!-- Article content -->
7 </article>
如果你的<header>标签只包含一个标题元素时,就不要使用<header>标签了.<article>标签肯定会让你的标题在文档大纲中显现出来,而且因为<header>并不包含多重内容(就像定义中描述的那样子),我们为何要增加而外的代码呢?应该像下面这样简单才可以:
1 <article>
2 <h1>My best blog post</h1>
3 <!-- Article content -->
4 </article>
<hgroup>不合理使用