DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5詳解
HTML5 標籤常見誤用盤點:別再把 section 當成 div 用
編輯:HTML5詳解     

HTML5 至今仍在演進,新標籤的定義時有調整,標籤的加入與移除也相當頻繁(hgroup 就是最典型的例子)。加上大型入口網站可參考的範例不多,學習過程往往只能靠自己摸索。以下整理幾個常見的小錯誤與不良實務,讓我們在往後的專案裡繞開這些坑。

不要把 section 當成萬用容器來寫樣式

最常見的錯誤之一,就是把原本的 div 一律改寫成 section,特別是那些只用來包住整個版面的外層容器。在 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 之後,很容易出現下面這種寫法:

<!-- Don't copy this code! It's wrong! -->
<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 並不是一個容器。它是帶有語意的大綱區段,用來描述文件的結構層次,而且應該要有自己的標題。當你只是想找一個元素來包住整個頁面,通常直接把樣式寫在 body 上就好,正如 Kroc Camen 所描述的做法;如果確實需要額外的元素來掛樣式,那就用 div——就像 Dr Mike 說的,div 並沒有滅亡,在沒有更合適選擇的時候,它往往就是最合適的那一個。

依這個原則修正後,結構應該長這樣(是否還需要額外的 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 與 footer 明確標示了頁首頁尾,aside 表達了「補充資訊」的語意,而純粹為了排版而存在的外層容器,則老實交回給 div,並用 role 屬性補上 landmark 資訊,讓輔助技術也能理解。標籤的選擇應該回應內容本身的意義,而不是把舊寫法逐字替換。

如果你仍然拿不主意用哪一個元素,建議直接查閱 HTML5 sectioning content element flowchart,讓這張流程圖替你做判斷。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved