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?
a <div> is a logical division in your content, semantically this would be my first choice if I wanted to group the heading with the list:
then you can use the following css to style everything together as one unit
According to w3.org (note that this link is in the long-expired draft HTML 3.0 spec):
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
Try defining a new class, ulheader, in css. p.ulheader ~ ul selects all that immediately follows My Header
In this case I would use a definition list as so:
Your first option is the good one. It's the least problematic one and you've already found the correct reasons why you couldn't use the other options.
By the way, your heading IS explicitly associated with the
<ul>
: it's right before the list! ;)edit: Steve Faulkner, one of the editors of W3C HTML5 and 5.1 has sketched out a definition of an
lt
element. That's an unofficial draft that he'll discuss for HTML 5.2, nothing more yet.