Can I get the CSS counter value of the parent?

后端 未结 3 1136
一向
一向 2021-02-06 09:54

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 t

相关标签:
3条回答
  • 2021-02-06 10:44

    See this: there is no way to do such things in CSS, obviously you would need to use JavaScript for it but pseudo-elements are not in the DOM afaik. As for the other answers: he wants the value of the counter that appears before the list items.

    0 讨论(0)
  • 2021-02-06 10:52

    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

    0 讨论(0)
  • 2021-02-06 10:52

    No, CSS doesn't support such "variable" things. All you can do is set the same style as parent.

    0 讨论(0)
提交回复
热议问题