CSS counter-set 属性

定义和用法

counter-set 属性用于创建并将 CSS 计数器设置为特定值。

counter-set 属性通常与 counter-increment 属性和 content 属性一起使用。

实例

例子 1

创建一个计数器("my-counter"),将其设置为 5,并在每次出现 <h2> 选择器时将其增加 1:

body {
  /* 将 "my-counter" 设置为 5 */
  counter-set: my-counter 5;
}

h2::before {
  /* 将 "my-counter" 增加 1 */
  counter-increment: my-counter;
  content: "Section " counter(my-counter) ". ";
}

亲自试一试

例子 2

创建一个计数器("my-counter"),将其设置为 5,并在每次出现 <h2> 选择器时将其减少 1:

body {
  /* 将 "my-counter" 设置为 5 */
  counter-set: my-counter 5;
}

h2::before {
  /* 将 "my-counter" 减少 1 */
  counter-increment: my-counter -1;
  content: "Section " counter(my-counter) ". ";
}

亲自试一试

例子 3

使用 "Section 10:"、"10.1"、"10.2" 等格式为章节和子章节编号:

body {
  /* 将 "section" 设置为 9 */
  counter-set: section 9;
}

h1 {
  /* 将 "subsection" 设置为 0 */
  counter-set: subsection 0;
}

h1::before {
  /* 将 "section" 增加 1 */
  counter-increment: section;
  content: "Section " counter(section) ": ";
}

h2::before {
  /* 将 "subsection" 增加 1 */
  counter-increment: subsection;
  content: counter(section) "." counter(subsection) " ";
}

亲自试一试

例子 4

创建一个计数器,将其设置为 9,并在每次出现 <h2> 选择器时将其增加 1(使用罗马数字):

body {
  /* 将 "my-counter" 设置为 9 */
  counter-set: my-counter 9;
}

h2::before {
  /* 将 "my-counter" 增加 1 */
  counter-increment: my-counter;
  content: counter(my-counter, upper-roman) ". ";
}

亲自试一试

CSS 语法

counter-set: none|counter-name number|initial|inherit;

属性值

描述
none 默认值。不设置计数器。
counter-name number

要设置的计数器名称及其值。

每次出现选择器时,计数器将被设置为该值。

默认数值为 0。

initial 将此属性设置为其默认值。参阅 initial
inherit 从其父元素继承此属性。参阅 inherit
默认值: none
继承性:
动画制作: 不支持。请参阅:动画相关属性
版本: CSS2
JavaScript 语法: object.style.counterSet="4"

浏览器支持

表格中的数字注明了完全支持该属性的首个浏览器版本。

Chrome Edge Firefox Safari Opera
85 85 68 17.2 71

相关页面

参考:::before 伪元素

参考:::after 伪元素

参考:CSS content 属性

参考:CSS counter-increment 属性

参考:CSS counter() 函数