Search code examples
htmlsemantic-uifomantic-ui

Does HTML5 allow a block-level element (like div) inside a heading (like h1)?


I would always have said no, but then I came across this code from Semantic UI (and Fomantic UI), a very popular front-end framework:

<h2 class="ui icon header">
  <i class="settings icon"></i>
  <div class="content">
    Account Settings
    <div class="sub header">Manage your account settings and set e-mail preferences.</div>
  </div>
</h2>

The code struck me as unusual for two reasons: (1) the <i> tag has been repurposed as a generic hook for an icon, and (2) there's that nested <div> sitting right there inside the <h2> element. I question the semantics of the first, and the validity of the second.

Now I suppose the code works in all major browsers or they wouldn't have used it, but it hardly seems idiomatic. More importantly, is it even valid?


Note: I used the term 'block-level element' in the question (which everyone understands), but as MDN docs point out:

The distinction of block-level vs. inline elements was used in HTML specifications up to 4.01. In HTML5, this binary distinction is replaced with a more complex set of content categories. While the "inline" category roughly corresponds to the category of phrasing content, the "block-level" category doesn't directly correspond to any HTML5 content category, but "block-level" and "inline" elements combined together correspond to the flow content in HTML5.


Solution

  • This is nasty code, completely off spec. Inside of a h2 you can only have inline elements phrasing content elements like span, strong, em, etc. The <i> tag is often used for icons though, so nothing shocking about that. But the divs ...? Shockingly bad. Switch them to <span> and the code would be valid.

    Here's the official spec of what h1, h2, etc. can contain. So-called "phrasing content": https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#phrasing_content

    Edit: MDN is not the official spec, as noted by the original poster in the comments. It is however based on the official spec. The authoritative source on HTML is supposedly the HTML Living Standard from Web Hypertext Application Technology Working Group (WHATWG). They offer good information about phrasing content and headings (h1-h6).