介绍
counter 有点像 JS 的 for loop index. 最常用到的地方就是做 ol > li.
参考:
默认 ol > li
<ol> <li> Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. </li> <li>Lorem ipsum dolor sit amet.</li> </ol>
效果
1, 2 号码是默认的, 如果我想在 number 前面加上 Step 字眼:
可以通过 CSS
ol { padding-left: 7ch; li { &::marker { content: "Step " counter(list-item) ": "; } } }
这里就用到了 counter
reset, increment, counter()
它的 3 步骤就是 declare/reset, increase, use it.
ol { padding-left: 7ch; counter-reset: my-counter; // index = 0 li { counter-increment: my-counter; // index++ &::marker { content: "Step " counter(my-counter) ": "; // get index } } }
每当遇到 ol, 它就会 reset 1 个新的 variable.
li 就 increase
::marker 时就调用输出.
输出不同格式
输出的时候还可以选择各做格式, 比如 alphabet, decimal 等等
&::marker { content: "Step " counter(my-counter, lower-alpha) ": "; // get index }
在第 2 参数写上 lower-alpha, 就会输出 a, b, c 了. (注: zero 输出 alpha 还是 zero 哦)
可以参考 list-style-type, 全都可以用在 counter 参数格式
层中层
CSS Style
ol { counter-reset: section; list-style-type: none; } li::before { counter-increment: section; content: counters(section,".") " "; }
关键在 "."