一、不要使用section作為div的替代品
人們?cè)跇?biāo)簽使用中最常見(jiàn)到的錯(cuò)誤之一就是隨意將HTML5的<section>等價(jià)于<div>——具體地說(shuō),就是直接用作替代品(用于樣式)。在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中,會(huì)是這樣:
請(qǐng)不要復(fù)制這些代碼!這是錯(cuò)誤的!
<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)容中用來(lái)幫助構(gòu)建文檔概要的語(yǔ)義部分。它應(yīng)該包含一個(gè)頭部。如果你想找一個(gè)用作頁(yè)面容器的元素(就像HTML或者XHTML的風(fēng)格),那么考慮如Kroc Camen所說(shuō),直接把樣式寫(xiě)到body元素上吧。如果你仍然需要額外的樣式容器,還是繼續(xù)使用div吧。
基于上述思想,下面才是正確的使用HTML5和一些ARIA roles特性的例子(注意,根據(jù)你自己的設(shè)計(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>
二、只在需要的時(shí)候使用header和hgroup
寫(xiě)不需要寫(xiě)的標(biāo)簽當(dāng)然是毫無(wú)意義的。不幸的是,我經(jīng)常看到header和hgroup被無(wú)意義的濫用。你可以閱讀一下關(guān)于header和hgroup元素的兩篇文章做一個(gè)詳細(xì)的了解,其中內(nèi)容我簡(jiǎn)單總結(jié)如下:
- header元素表示的是一組介紹性或者導(dǎo)航性質(zhì)的輔助文字,經(jīng)常用作section的頭部
- 當(dāng)頭部有多層結(jié)構(gòu)時(shí),比如有子頭部,副標(biāo)題,各種標(biāo)識(shí)文字等,使用hgroup將h1-h6元素組合起來(lái)作為section的頭部
- header的濫用
由于header可以在一個(gè)文檔中使用多次,可能使得這樣代碼風(fēng)格受到歡迎:
請(qǐng)不要復(fù)制這段代碼!此處并不需要header –>
<header> <h1>My best blog post</h1> </header> <!-- Article content --></article>
如果你的header元素只包含一個(gè)頭部元素,那么丟棄header元素吧。既然article元素已經(jīng)保證了頭部會(huì)出現(xiàn)在文檔概要中,而header又不能包含多個(gè)元素(如上文所定義的),那么為什么要寫(xiě)多余的代碼。簡(jiǎn)單點(diǎn)寫(xiě)成這樣就行了:
<article> <h1>My best blog post</h1> <!-- Article content --></article>
的錯(cuò)誤使用
在headers這個(gè)主題上,我也經(jīng)常看到hgroup的錯(cuò)誤使用。有時(shí)候不應(yīng)該同時(shí)使用hgroup和header:
- 如果只有一個(gè)子頭部
- 如果hgroup自己就能工作的很好。。。這不廢話么
第一個(gè)問(wèn)題一般是這樣的:
請(qǐng)不要復(fù)制這段代碼!此處不需要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>
第二個(gè)問(wèn)題是另一個(gè)不必要的例子:
請(qǐng)不要復(fù)制這段代碼!此處不需要header –>
<hgroup> <h1>My company</h1> <h2>Established 1893</h2> </hgroup></header>