之前在实现代码行号的时候发现 CSS 有个很方便的功能“计数器”,可以很方便的生成代码行号以及章节号,本文介绍一些这些功能。
css 计数器有三部分组成: counter-reset
、counter-increment
两个属性和函数 counter()/counters()
。下面介绍一下它们的使用。
counter-reset
使用计数器前需要使用 counter-reset
声明一个或多个计数器:
counter-reset: counter-name [initValue] [counter-name2 [initValue2]] …[counter-nameN [initValueN]];
参数:
counter-name
不能为none
、unset
、inherit
和initial
否则会被忽略。initValue
必须为整数,默认值为 0,可以省略。
示例:
/* Set counter-name to 0 */ |
counter-increment
counter-increment 可以增加或者减小一个或者多个计数器的值:
counter-increment: counter-name [changeValue] [counter-name2 [changeValue2]] …[counter-nameN [changeValueN]];
参数:
counter-increment
不能为none
、unset
、inherit
和initial
否则会被忽略。changeValue
必须为整数,可以为整数或者负数,如果为负数则减小计数器的值。
示例:
/* Increment counter-name by 1 */ |
counter()/counters()
计数器的值可以通过设置 content 属性值为 counter()/counters() 展示:
content: [‘prefix’]counter(section, [style])[‘suffix’];
content: [‘prefix’]counters(section, [‘join-string’], [style])[‘suffix’];
counter()
函数有两种使用形式:counter(name)
或counter(name, style)
。生成的文本是指定伪元素范围内由指定的字符串(prefix、string、suffix 参数)连接起来计数器的值。counters()
函数也有两种形式:counter(name, string)
或counters(name, string, style)
。生成的文本是指定的伪元素的范围内的所有指定名称计数器的值, 从最外层到最内层, 由指定的字符串(prefix、string、suffix 参数)连接起来。
其中 style
支持 list-style
的取值。
具体使用示例看下一节。
使用示例
计数器主要有以下使用场景:
显示行号
See the Pen 计数器-行号 by tcatche (@tcatche) on CodePen.
显示层级的章节号
See the Pen 多个计数器嵌套 by tcatche (@tcatche) on CodePen.
更改计数器的样式
See the Pen 章节 by tcatche (@tcatche) on CodePen.