CSS counter-reset on nested list

后端 未结 3 794
天命终不由人
天命终不由人 2020-12-10 04:09

I\'m struggling with counter-reset when ol is in div. Red list in the snippet numbering should be:

1, 2, 3

not:

3条回答
  •  生来不讨喜
    2020-12-10 04:40

    Your issue isn't with the counter-reset property, it is with the content property and the counters() function. This function atomaticaly adds a new instance for each nested element. This is great for the nested ol elements but it also adds a counter instance when the first level ol is nested in any other element.

    So you should use the counter() function on the first level ol elements and keep the counters() (notice the "s") function on the second level one :

    More info on MDN about nesting counters

    ol {
        counter-reset: item;
        list-style: none;
    }
    li:before {
        counter-increment: item;
        content: counter(item)". ";
    }
    ol ol li:before{
      content: counters(item,".") " ";
    }
    1. BBD
    2. BBD
      1. BBD
      2. BBD
      3. BBD
    3. BBD
    1. BBD
    2. BBD
    3. BBD
    1. BBD
    2. BBD
    3. BBD


    As suggested by @harry, you can also set the counter reset on the first child of the ol element, either with the li:first-child pseudo class or with the ol::before pseudo element, example :

    ol{
        list-style: none;
    }
    li:first-child{
        counter-reset: item;
    }
    /* or
    ol:before {
        content: '';
        counter-reset: item;
    }
    */
    li:before {
        counter-increment: item;
        content: counters(item, ".")" ";
    }
    1. BBD
    2. BBD
      1. BBD
      2. BBD
      3. BBD
    3. BBD
    1. BBD
    2. BBD
    3. BBD
    1. BBD
    2. BBD
    3. BBD

提交回复
热议问题