tags:

views:

193

answers:

3

Hi,

I have an ordered list in HTML. I would like to add styling only to the numbers (1,2,3,...), and not to the list items themselves.

Is there a way to refer to these numbers ?

Thanks !

+2  A: 

Yes, you simply style the ol element and then override the style on the li element.

ol
{
    color: blue;
    font-style: italic;
}
ol li p
{
    color: black;
    font-style: normal;
}

with

<ol>
    <li><p>Text</p></li>
    <li><p>Text</p></li>
    <li><p>Text</p></li>
</ol>

You can change the p tags to <divs> if you want, but if you keep them as p's you'll have to strip margins and paddings.

Josh K
-1: Doesn't work, at least on Chrome and Firefox. E.g.: http://jsbin.com/oyeya/edit
Max Shawabkeh
Try it now, I forgot the `p` tags.
Josh K
Works now. Vote reverted.
Max Shawabkeh
Thanks !How about changing the background color of the numbers ?I would like the numbers to be with a red background and the text to be without any background. Is that possible ?
Misha Moroshko
@misha: I'm not sure if that's possible, though it's defenitely a good point. [This as about as close as I could get](http://jsbin.com/oyeya/2). Though you could also strip paddings and margins and then adjust with some other divs around the `<li>` tags maybe.
Josh K
+1  A: 

CSS2 provides for control over generated content, which will let you style the auto-generated content independently of the rest of the item using the :before pseudoclass. Here's a solution that meet's the OP's follow-up criteria (background color on the list enumerator but not the item).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head profile="http://gmpg.org/xfn/11"&gt;

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <style type="text/css">

    body { margin: 0; padding: 10px; }
    ol {
        counter-reset: item; 
        margin: 0;
        padding: 0;
    }
    li {
        display: block;
        padding: 10px 0;
        margin: 0 0 10px 0;
    }
    li:before { 
        content: counter(item);
            /* 
                To generate punctuation after the number, just precede or follow with a string: 
                content: "Chapter " counter(item) " >> ";  

                To make nested counters (1, 1.1, 1.1.1, etc.), use:
                content: counters(item, ".");
            */
        counter-increment: item; 

        background-color: #ddd;
        margin-right: 15px;
        padding: 10px;
    }
    ol li ol { margin-bottom: -10px; padding-top: 10px; }
    ol li ol li { margin: 10px 0 0 30px; }

    </style>
</head>

<body>

<ol>
    <li>Turtles</li>
    <li>Lizards
        <ol>
            <li>Salamanders</li>
            <li>Geckos</li>
        </ol>
    </li>
    <li>Velociraptors</li>
</ol>

</body>
</html>
cowbellemoo