如何用CSS/SASS实现TOC计数器小于10补0、≥10不补0(无需JS)
解决方案
方法一:使用CSS计数器内置格式(推荐)
直接利用CSS计数器的decimal-leading-zero格式规则,它会自动为小于10的数字添加前导零,大于等于10的数字正常显示,完全满足需求,且无需依赖元素位置选择器,不受同级其他li元素影响。
注意:你原代码中SCSS的类名toc-item-h2和HTML的toc-item-2不匹配,需要统一类名才能生效,以下是修正后的代码:
ul.toc-wrapper { counter-reset: my-counter 0; // 统一类名为toc-item-h2(也可根据HTML调整为toc-item-2) li.toc-item-h2 { &::before { counter-increment: my-counter; // 使用decimal-leading-zero自动处理前导零 content: counter(my-counter, decimal-leading-zero) ":"; padding-right: 8px; } } li.toc-item-h3 { // 可添加h3的子编号逻辑(示例) counter-reset: sub-counter 0; &::before { counter-increment: sub-counter; content: counter(my-counter) "." counter(sub-counter) ":"; padding-right: 8px; margin-left: 16px; } } }
对应的HTML(统一类名后):
<ul class="toc-wrapper"> <li class="toc-item-h2">some heading</li> <li class="toc-item-h3">aaaa</li> <li class="toc-item-h3">bbbb</li> <li class="toc-item-h2">hoge heading</li> <li class="toc-item-h3">cccc</li> <li class="toc-item-h3">dddd</li> <!-- 更多项 --> </ul>
最终效果:
01: some heading 1.1: aaaa 1.2: bbbb 02: hoge heading 2.1: cccc 2.2: dddd ... 09: piyo heading 10: aaaa heading
方法二:SCSS循环生成规则(兼容极端旧浏览器)
若需兼容不支持decimal-leading-zero的极旧浏览器(目前几乎无需考虑),可利用SCSS循环生成前9个h2项的特殊样式。但此方法依赖元素位置,若同级有其他li元素会导致选中错误,仅作备选:
ul.toc-wrapper { counter-reset: my-counter 0; li.toc-item-h2 { &::before { counter-increment: my-counter; content: counter(my-counter) ":"; padding-right: 8px; } } // 为前9个toc-item-h2添加前导零 @for $i from 1 through 9 { ul.toc-wrapper li.toc-item-h2:nth-of-type(#{$i}) { &::before { content: "0" counter(my-counter) ":"; } } } }
内容的提问来源于stack exchange,提问作者yasuda_t
相关产品推荐
相关产品推荐

