讓 HTML 結構更清晰、更規範,是每個前端開發者都該具備的思維。本文就來談談如何藉由 HTML5 的優化思路,打造語義化的頁面骨架。
HTML5 新增了一些元素,用來標識常見的頁面結構,讓 HTML 更具語義。然而,由於瀏覽器支援普及需要時間,這些元素我們往往無法立即全面採用。既然如此,不妨效法微格式(Microformats)的做法,用 class 或 id 命名來代替,讓自己的結構更加清晰。這套約定一旦推廣開來,就能形成團隊共用的規範,讓協作更加順暢。
◎ section:可以是書中的一章或一節,實際上泛指在 HTML4 中擁有自己標題的任何區塊
◎ header:頁面上顯示的頁首;與 head 元素不同
◎ footer:頁尾;例如電子郵件中的簽名
◎ nav:指向其他頁面的一組連結
◎ article:blog、雜誌、文章匯編等中的一篇文章
HTML5 的文檔結構:
<header>...</header>
<nav>...</nav>
<article>
<section> ... </section>
</article>
<aside>...</aside>
<footer>...</footer>
對應的 XHTML 文檔結構:
<div id="header">header</div>
<div id="nav">nav</div>
<div class="article">
<div class="section">section</div>
</div>
<div id="aside">aside</div>
<div id="footer">footer</div>
HTML5 的圖片結構:
<figure id="fig2">
<legend>Figure 2. Install Mozilla XForms dialog</legend>
<img alt="A Web site is requesting permission to install the following item: Mozilla XForms 0.7 Unsigned" src="installdialog.jpg" />
</figure>
對應的 XHTML 圖片結構:
<div class="figure">
<h4 class="legend">Figure 2. Install Mozilla XForms dialog</h4>
<img alt="A Web site is requesting permission to install the following item: Mozilla XForms 0.7 Unsigned" src="installdialog.jpg" />
</div>
m 元素表示文本被「加上標誌」,但並不一定帶有強調意味,可以把它想像成書中被螢光筆標示出來的一節。Google 的網頁快取頁面就是典型案例——當你連到一個快取副本時,搜尋詞就會被加上標記。舉例來說,如果搜尋「Egret」,那麼 Google 的快取頁面可能長得像這樣:
HTML5:
The Great <m>Egret</m> (also known as the American <m>Egret</m>) is a large white wading bird found worldwide. The Great <m>Egret</m> flies with slow wing beats. The scientific name of the Great <m>Egret</m> is Casmerodius albus.
對應的 XHTML:
The Great <span class="m">Egret</span> (also known as the American <span class="m">Egret</span>) is a large white wading bird found worldwide. The Great <span class="m">Egret</span> flies with slow wing beats. The scientific name of the Great <span class="m">Egret</span> is Casmerodius albus.
由此可見,語義化的核心精神,就是讓標籤的選擇貼近內容本身的含義,而非僅為了呈現外觀。