CSS counter-reset on nested list

隐身守侯 提交于 2019-11-29 03:59:58
web-tiki

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,".") " ";
}
<ol>
    <li>BBD</li>
    <li>BBD
        <ol>
            <li>BBD</li>
            <li>BBD</li>
            <li>BBD</li>
        </ol>
    </li>
    <li>BBD</li>
</ol>

<ol>
    <li>BBD</li>
    <li>BBD</li>
    <li>BBD</li>
</ol>

<div>
    <ol style="color:red;">
        <li>BBD</li>
        <li>BBD</li>
        <li>BBD</li>
    </ol>
</div>

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, ".")" ";
}
<ol>
    <li>BBD</li>
    <li>BBD
        <ol>
            <li>BBD</li>
            <li>BBD</li>
            <li>BBD</li>
        </ol>
    </li>
    <li>BBD</li>
</ol>

<ol>
    <li>BBD</li>
    <li>BBD</li>
    <li>BBD</li>
</ol>

<div>
    <ol style="color:red;">
        <li>BBD</li>
        <li>BBD</li>
        <li>BBD</li>
    </ol>
</div>
npit

You have to reset the div
And "not reset" the ol
Like this:

<div style="color:red;counter-reset: item;">
    <ol style="color:red;counter-reset: none;" id="test">
        <li>BBD</li>
        <li>BBD</li>
        <li>BBD</li>
    </ol>
</div>

One way to work this around would be to add a class (since you cannot select an element based on what is its parent), and exclude it from initial selection with :not pseudo-class:

HTML:

<ol>
    <li>BBD</li>
    <li>BBD
        <ol>
            <li>BBD</li>
            <li>BBD</li>
            <li>BBD</li>
        </ol>
    </li>
    <li>BBD</li>
</ol>

<ol>
    <li>BBD</li>
    <li>BBD</li>
    <li>BBD</li>
</ol>

<div>
    <ol class="x" style="color:red;">
        <li>BBD</li>
        <li>BBD</li>
        <li>BBD</li>
    </ol>
</div>   

CSS:

ol:not(.x) {
    counter-reset: item;
    list-style: none;
}
ol:not(.x) li:before {
    counter-increment: item;
    content: counters(item, ".")" ";
}   

as per this JSFiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!