Question

What is the proper way to provide a semantic caption for an HTML list? For example, the following list has a "title"/"caption".

Fruit

  • Apple
  • Pear
  • Orange

How should the word "fruit" be handled, in a such way that it is semantically associated with the list itself?

Was it helpful?

Solution

While there is no caption or heading element structuring your markup effectively can have the same effect. Here are some suggestions:

Nested List

<ul>
    <li>
        Fruit
        <ul>
            <li>Apple</li>
            <li>Pear</li>
            <li>Organge</li>
        </ul>
    </li>
</ul>

Heading Prior to List

<hX>Fruit</hX>
<ul>
    <li>Apple</li>
    <li>Pear</li>
    <li>Orange</li>
</ul>

Definition List

<dl>
  <dt>Fruit</dt>
  <dd>Apple</dd>
  <dd>Pear</dd>
  <dd>Orange</dd>
</dl>

OTHER TIPS

Option 1

HTML5 has the figure and figcaption elements, which I find work quite nicely.

Example:

<figure>
    <figcaption>Fruit</figcaption>
    <ul>
        <li>Apple</li>
        <li>Pear</li>
        <li>Orange</li>
    </ul>
</figure>

These are then easily styled with CSS.


Option 2

Using CSS3's ::before pseudo-element can be a nice solution:

HTML:

<ul title="Fruit">
    <li>Apple</li>
    <li>Pear</li>
    <li>Orange</li>
</ul>

CSS:

ul[title]::before {
    content: attr(title);
    /* then add some nice styling as needed, eg: */
    display: block;
    font-weight: bold;
    padding: 4px;
}

You can, of course, use a different selector than ul[title]; for example, you could add a 'title-as-header' class and use ul.title-as-header::before instead, or whatever you need.

This does have the side effect of giving you a tooltip for the whole list. If you don't want such a tooltip, you could use a data attribute instead (e.g., <ul data-title="fruit"> and ul[data-title]::before { content: attr(data-title); }).

As far as I know, there are no provisions in current HTML specs for providing a caption for a list, as there are with tables. I'd stay with using either a classed paragraph, or a header tag for now.

<h3>Fruit</h3>
<ul>
    <li>Apple</li>
    <li>Pear</li>
    <li>Orange</li>
</ul>

In the future, when HTML5 gains wider adoption, you will be able to use the <legend> and <figure> tags to accomplish this slightly more semantically.

See this post on the W3C mailing list for more information.

There is no caption-like tag for a list like a table has. So I'd just give it an <Hx> (x depending on your previously used headers).

You can always use <label/> to associate label to your list element:

<div>
    <label for="list-2">TEST</label>
    <ul id="list-1">
        <li>one</li>
        <li>two</li>
        <li>three</li>
    </ul>
    <label for="list-2">TEST</label>
    <ol id="list-2">
        <li>one</li>
        <li>two</li>
        <li>three</li>
    </ul>
</div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top