Css global counters

According to css spec ( http://www.w3.org/TR/CSS21/generate.html#scope ), resetting the counter automatically creates a new counter instance.

I am trying to circumvent this behavior in order to handle global counters that would not consider the structure of the div tree when reset.

See example below.

css

body {
    counter-reset: counter1 0 counter2 0;
}

.counter1 {
    counter-increment: counter1;
    counter-reset: counter2 0;
}

    .counter1:before {
        content: counter(counter1);
    }

.counter2 {
    counter-increment: counter2;
}

    .counter2:before {
        content: counter(counter1) ". " counter(counter2);
    }
<body>
    <div>
        <div class="counter1">Section 1</div>
        <div class="counter2">SubItem 1.1</div>
    </div>
    <div>
        <div class="counter2">SubItem 1.2</div>
    </div>
    <div>
        <div class="counter2">SubItem 1.3</div>
    </div>
    <div>
        <div class="counter1">Section 2</div>
        <div class="counter2">SubItem 2.1</div>
    </div>
    <div>
        <div class="counter2">SubItem 2.2</div>
    </div>
</body>
Run code

Any ideas?

+4
source share
1 answer

You need something like this http://jsfiddle.net/9x492j2m/

You can have your items in the ul list.

<ul class="counter1">
    <li>Section 1
        <ul class="counter2">
            <li>SubItem 1.1</li>
            <li>SubItem 1.2</li>
            <li>SubItem 1.3</li>
        </ul>
    </li>
    <li>Section 2
        <ul class="counter2">
            <li>SubItem 2.1</li>
            <li>SubItem 2.2</li>
            <li>SubItem 2.3</li>
            <li>Subitem 2.4</li>
        </ul>
    </li>
</ul>

And then CSS

.counter1 {
    counter-reset: counter1;   
    list-style: none;
}
.counter1 li:before {
    content: counter(counter1);
    counter-increment:counter1;
    color: #fff;
    background: red;    
}
.counter2 {
    counter-reset: counter2;    
}
.counter2 li:before {
    content: counter(counter1)". " counter(counter2);
    counter-increment:counter2;
}
0
source

All Articles