一、不要使用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>
而現在在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>並不是樣式容器。section元素表示的是內容中用來幫助構建文件概要的語義部分。它應該包含一個頭部。如果你想找一個用作頁面容器的元素(就像HTML或者XHTML的風格),那麼考慮如Kroc Camen所說,直接把樣式寫到body元素上吧。如果你仍然需要額外的樣式容器,還是繼續使用div吧。
基於上述思想,下面才是正確的使用HTML5和一些ARIA roles特性的例子(注意,根據你自己的設計,你也可能需要加入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>
如果你還是無法確定使用哪種元素,那麼我建議你參考HTML5 sectioning content element flowchart
二、只在需要的時候使用header和hgroup
寫不需要寫的標籤當然是毫無意義的。不幸的是,我經常看到header和hgroup被無意義的濫用。你可以閱讀一下關於header和hgroup元素的兩篇文章做一個詳細的瞭解,其中內容我簡單總結如下:
header元素表示的是一組介紹性或者導航性質的輔助文字,經常用作section的頭部
當頭部有多層結構時,比如有子頭部,副標題,各種標識文字等,使用hgroup將h1-h6元素組合起來作為section的頭部
header的濫用
由於header可以在一個文件中使用多次,可能使得這樣程式碼風格受到歡迎:
<!-- 請不要複製這段程式碼!此處並不需要header --><article> <header> <h1>My best blog post</h1> </header> <!-- Article content --></article>
如果你的header元素只包含一個頭部元素,那麼丟棄header元素吧。既然article元素已經保證了頭部會出現在文件概要中,而header又不能包含多個元素(如上文所定義的),那麼為什麼要寫多餘的程式碼。簡單點寫成這樣就行了:
<article> <h1>My best blog post</h1> <!-- Article content --></article>
<hgroup>的錯誤使用
在headers這個主題上,我也經常看到hgroup的錯誤使用。有時候不應該同時使用hgroup和header:
如果只有一個子頭部
如果hgroup自己就能工作的很好。。。這不廢話麼
第一個問題一般是這樣的:
<!-- 請不要複製這段程式碼!此處不需要hgroup --><header> <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 --><header> <hgroup> <h1>My company</h1> <h2>Established 1893</h2> </hgroup></header>
如果header唯一的子元素是hgroup,那還要header幹神馬?如果header中沒有其他的元素(比如多個hgroup),還是直接拿掉header吧
<hgroup> <h1>My company</h1> <h2>Established 1893</h2></hgroup>