Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the CSS counter value of the parent?

Tags:

css

I need to implement the following list style:

01 Item 1
02 Item 2
    02a Item 2a
    02b Item 2b
03 Item 3

How can I get the counter value of the parent to use in the :before content of my sub item? (02 in my above example)

like image 525
Colin Avatar asked Nov 18 '11 18:11

Colin


People also ask

Which CSS counter property creates or resets a counter?

The counter-reset CSS property resets a CSS counter to a given value. This property will create a new counter or reversed counter with the given name on the specified element. Normal counters have a default initial value of 0.

How do you counter in CSS?

To use a counter it must first be initialized to a value with the counter-reset property. The counter's value can then be increased or decreased using counter-increment property. The current value of a counter is displayed using the counter() or counters() function, typically within a pseudo-element content property.

Can I use CSS counter in Calc?

The calc function does not permit the use of counter functions as its components. From the specs here - https://www.w3.org/TR/css3-values/#calc-notation: Components of a calc() expression can be literal values or attr() or calc() expressions. There have been many requests for this but always declined.


1 Answers

You use two different counters: one for the li parents and one for the li subitems. Then, in each li subitem, concatenate multiple counter() functions using each counter, like this:

ol {
    counter-reset: item;
}

ol ol {
    counter-reset: subitem;
}

li {
    display: block;
}

/* First level of parent items */
li:before {
    content: counter(item, decimal-leading-zero) ' ';
    counter-increment: item;
}

/* Second level of subitems */
li li:before {
    /* counter(item) for the parents, counter(subitem) for the subitems */
    content: counter(item, decimal-leading-zero) counter(subitem, lower-alpha) ' ';
    counter-increment: subitem;
}

jsFiddle demo, tested in all browsers that support :before and CSS2.1 counters including IE8+

Useful reading: W3C CSS2.1 generated content spec, §12.4.1 Nested counters and scope

like image 81
BoltClock Avatar answered Oct 06 '22 00:10

BoltClock