Html – How to semantically add heading to a list

htmlhtml-lists

This has been bothering me for a while, and I'm wondering if there's any consensus on how to do this properly. When I'm using an HTML list, how do I semantically include a header for the list?

One option is this:

<h3>Fruits I Like:</h3>
<ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Oranges</li>
</ul>

but semantically the <h3> heading is not explicitly associated with the <ul>

Another option is this:

<ul>
    <li><h3>Fruits I Like:</h3></li>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Oranges</li>
</ul>

but this seems a bit dirty, as the heading is not really one of the list items.

This option is not allowed by the W3C:

<ul>
    <h3>Fruits I Like:</h3>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Oranges</li>
</ul>

as <ul>'s can only contain one or more <li>'s

The old "list heading" <lh> makes the most sense

<ul>
    <lh>Fruits I Like:</lh>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Oranges</li>
</ul>

but of course it's not officially part of HTML

I've heard it suggested that we use <label> just like a form:

<ul>
    <label>Fruits I Like:</label>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Oranges</li>
</ul>

but this is a little strange and will not validate anyway.

It's easy to see the semantical problems when trying to style my list headers, where I end up needing to put my <h3> tags within the first <li> and target them for styling with something like:

ul li:first-of-type {
    list-style: none;
    margin-left: -1em;
    /*some other header styles*/
}

horrors! But at least this way I can control the entire <ul>, heading and all, by styling the ul tag.

What is the correct way to do this? Any ideas?

Best Answer

As Felipe Alsacreations has already said, the first option is fine.

If you want to ensure that nothing below the list is interpreted as belonging to the heading, that's exactly what the HTML5 sectioning content elements are for. So, for instance you could do

<h2>About Fruits</h2>
<section>
  <h3>Fruits I Like:</h3>
  <ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Oranges</li>
  </ul>
</section>
<!-- anything here is part of the "About Fruits" section but does not 
     belong to the "Fruits I Like" section. -->