一、不要使用section作為div的替代品
人們在標簽使用中最常見到的錯誤之一就是隨意將HTML5的<section>等價于<div>——具體地說,就是直接用作替代品(用于樣式)。在XHTML或者HTML4中,我們常看到這樣的代碼:
<!-- HTML 4-style code --><div id="wrapper"> <div id="header"> <h1>My super duper page</h1> Header content </div> <div id="main"> Page content </div> <div id="secondary"> Secondary content </div> <div id="footer"> Footer content </div></div>
而現(xiàn)在在HTML5中,會是這樣:
請不要復制這些代碼!這是錯誤的!
<section id="wrapper"> <header> <h1>My super duper page</h1> <!-- Header content --> </header> <section id="main"> <!-- Page content --> </section> <section id="secondary"> <!-- Secondary content --> </section> <footer> <!-- Footer content --> </footer></section>
這樣使用并不正確:**
并不是樣式容器。**section元素表示的是內(nèi)容中用來幫助構建文檔概要的語義部分。它應該包含一個頭部。如果你想找一個用作頁面容器的元素(就像HTML或者XHTML的風格),那么考慮如Kroc Camen所說,直接把樣式寫到body元素上吧。如果你仍然需要額外的樣式容器,還是繼續(xù)使用div吧。
基于上述思想,下面才是正確的使用HTML5和一些ARIA roles特性的例子(注意,根據(jù)你自己的設計,你也可能需要加入div)
<body><header> <h1>My super duper page</h1> <!-- Header content --></header><div role="main"> <!-- Page content --></div><aside role="complementary"> <!-- Secondary content --></aside><footer> <!-- Footer content --></footer></body>
二、只在需要的時候使用header和hgroup
寫不需要寫的標簽當然是毫無意義的。不幸的是,我經(jīng)常看到header和hgroup被無意義的濫用。你可以閱讀一下關于header和hgroup元素的兩篇文章做一個詳細的了解,其中內(nèi)容我簡單總結如下:
- header元素表示的是一組介紹性或者導航性質(zhì)的輔助文字,經(jīng)常用作section的頭部
- 當頭部有多層結構時,比如有子頭部,副標題,各種標識文字等,使用hgroup將h1-h6元素組合起來作為section的頭部
- header的濫用
由于header可以在一個文檔中使用多次,可能使得這樣代碼風格受到歡迎:
請不要復制這段代碼!此處并不需要header –>
<header> <h1>My best blog post</h1> </header> <!-- Article content --></article>
如果你的header元素只包含一個頭部元素,那么丟棄header元素吧。既然article元素已經(jīng)保證了頭部會出現(xiàn)在文檔概要中,而header又不能包含多個元素(如上文所定義的),那么為什么要寫多余的代碼。簡單點寫成這樣就行了:
<article> <h1>My best blog post</h1> <!-- Article content --></article>
的錯誤使用
在headers這個主題上,我也經(jīng)常看到hgroup的錯誤使用。有時候不應該同時使用hgroup和header:
- 如果只有一個子頭部
- 如果hgroup自己就能工作的很好。。。這不廢話么
第一個問題一般是這樣的:
請不要復制這段代碼!此處不需要hgroup –> <hgroup> <h1>My best blog post</h1> </hgroup> <p>by Rich Clark</p></header>
此例中,直接拿掉hgroup,讓heading果奔吧。
<header> <h1>My best blog post</h1> <p>by Rich Clark</p></header>
第二個問題是另一個不必要的例子:
請不要復制這段代碼!此處不需要header –>
<hgroup> <h1>My company</h1> <h2>Established 1893</h2> </hgroup></header>