超级面板
文章目录
最新文章
最近更新
文章分类
标签列表
文章归档

CSS 计数器:counter

之前在实现代码行号的时候发现 CSS 有个很方便的功能“计数器”,可以很方便的生成代码行号以及章节号,本文介绍一些这些功能。

css 计数器有三部分组成: counter-resetcounter-increment 两个属性和函数 counter()/counters()。下面介绍一下它们的使用。

counter-reset

使用计数器前需要使用 counter-reset 声明一个或多个计数器:

counter-reset: counter-name [initValue] [counter-name2 [initValue2]] …[counter-nameN [initValueN]];

参数:

  • counter-name 不能为 noneunsetinheritinitial 否则会被忽略。
  • initValue 必须为整数,默认值为 0,可以省略。

示例:

/* Set counter-name to 0 */
counter-reset: counter-name;

/* Set counter-name to -1 */
counter-reset: counter-name -1;

/* Set counter1 to 1, and counter2 to 4 */
counter-reset: counter1 1 counter2 4;

/* Sets the chapter and page counters to 0 and the section counter to 1. */
counter-reset: chapter section 1 page;

counter-increment

counter-increment 可以增加或者减小一个或者多个计数器的值:

counter-increment: counter-name [changeValue] [counter-name2 [changeValue2]] …[counter-nameN [changeValueN]];

参数:

  • counter-increment 不能为 noneunsetinheritinitial 否则会被忽略。
  • changeValue 必须为整数,可以为整数或者负数,如果为负数则减小计数器的值。

示例:

/* Increment counter-name by 1 */
counter-increment: counter-name;

/* Decrement counter-name by 1 */
counter-increment: counter-name -1;

/* Increment counter1 by 1, and decrement counter2 by 4 */
counter-increment: counter 1 counter2 -4;

/* Increases the value of the chapter and page counters by 1 and the section counter by 2. */
counter-increment: chapter section 2 page;

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.

参考