hgroup 是HTML5中新定義的元素,用來把標題與副標題群組。既然已經有 header 標籤,為什麼還需要 <hgroup>?以下就來解答這個問題。
根據規範:hgroup 通常用來把一個或多個 h1~h6 元素群組,例如把一個區塊的標題與隨附的副標題放在一起。
換句話說,<hgroup> 扮演一個容器的角色,可以包含一個或多個標題相關的元素(這些標題可能位於 <header> 之中),且只能包含 h1~h6 標題元素,它們可能是副標題、二選一的標題或標記標題。
更具體地說,可以透過幾個例子來理解:
當 article 只有一個標題時:
<article>
<h1>Article title</h1>
<p>Content…</p>
</article>
當 article 有一個標題,並含元資料(metadata)時:
<article>
<header>
<h1>Article title</h1>
<p>(<time datetime="2009-07-13">13th July, 2009</time>)</p>
</header>
<p>Content…</p>
</article>
當 article 有一組「標題+副標題」時,用 hgroup 群組:
<article>
<hgroup>
<h1>Article title</h1>
<h2>Article subtitle</h2>
</hgroup>
<p>Content…</p>
</article>
當同時有標題、副標題與元資料時,把 hgroup 放進 header:
<article>
<header>
<hgroup>
<h1>Article title</h1>
<h2>Article subtitle</h2>
</hgroup>
<p>(<time datetime="2009-07-13">13th July, 2009</time>)</p>
</header>
<p>Content…</p>
</article>
一切都源起於文檔大綱(document outline)。當標題被群組在 <hgroup> 中時,大綱演算法會忽略群組裡較低等級的標題,只把最高等級的標題納入大綱。例如:
<header>
<hgroup>
<h1><a href="/">Mini Apps</a></h1>
<h2>Web applications for iPhone, Android & other mobile platforms</h2>
</hgroup>
</header>
這裡 <hgroup> 雖包含 h1 與 h2,但大綱中只會出現 <h1>,副標題不會污染文檔結構。你可以透過線上工具檢視文檔大綱:https://gsnedders.html5.org/outliner/。
總結:只有一個標題元素時,不需要 <hgroup>;出現一個以上標題要群組時,才用 <hgroup> 包起來;當標題有副標題或其它與 section/article 相關的元資料時,就把 <hgroup> 和元資料一起放進獨立的 <header> 容器中。中文原文:HTML5 hgroup元素使用概述;英文原文:Avoiding common HTML5 mistakes。