screenshot

A quick post about how I style elements in lists (that are not the <li> itself) with the corresponding item number using a custom CSS counter.

I regularly use custom list styling like this for work on mozilla.org. Here is a simplified real-world example:

html

<ol>
    <li>
        <h3>Click on the Firefox installer.</h3>
        <div>
            <img src="..." alt="...">
        </div>
        <div>
            <p><strong>Look down, look left.</strong> Click on the Firefox installer in the lower bottom left-hand corner.</p>
        </div>
    </li>

    <li>
        <h3>Select ‘Yes.’</h3>
        <div>
            <img src="..." alt="...">
        </div>
        <div>
            <p>Click YES for Firefox. <strong>Select YES</strong> on the pop-up window to finish the install.</p>
        </div>
    </li>
</ol>

The native styling for these list items isn’t positioned where we would like. A better spot would be alongside the titles <h3>.

CSS

ol {
    counter-reset: list-counter;
    list-style: none;
}

Targeting the parent ordered list element <ol>, we set our custom CSS counter named list-counter to 0 via counter-reset

PRO-TIP: You can name this counter whatever you would like except list-item. It is a special keyword value for counters that will absolutely cause cross-browser counting issues. I learned this the hard way and discovered this “bug” via stackoverflow.

list-style: none is also included here to remove the default number display, which we will soon be replacing with our own custom version.

ol>li {
    counter-increment: list-counter;
}

Targeting all direct li children of the ol element to increment list-counter by 1.

h3::before {
    background: #4a4a55;
    border-radius: 50%;
    color: #ffffff;
    content: counter(list-counter);
    font-size: 1rem;
    line-height: 2.5rem;
    text-align: center;
    margin: 0 16px 16px 0;
    /*- any desired styles -*/
}

Now the fun part! 😎

We can use our dynamic variable of list-counter inside a counter() function to display the correct number value. I chose to do this by selecting the ::before pseudo-element which is the perfect vessel for inserting our list numbers via content: counter(list-counter).

/amy

☆ See a bug or typo? File a bug!