CSS counter-set 属性
示例
创建一个计数器(“my-counter”),将其设置为 5,并为 <h2> 选择器的每次出现增加一
body {
/* 将“my-counter”设置为 5 */
counter-set: my-counter 5;
}
h2::before {
/* 增加“my-counter” 1 */
counter-increment: my-counter;
content: "Section " counter(my-counter) ". ";
}
自己动手试一试 »
更多“自己尝试”的例子见下文。
定义和用法
counter-set
属性用于创建 CSS 计数器并将其设置为特定值。
counter-set
属性通常与 counter-increment 属性和 content 属性一起使用。
浏览器支持
表中的数字指定了完全支持该属性的第一个浏览器版本。
属性 | |||||
---|---|---|---|---|---|
counter-set | 85 | 85 | 68 | 17.2 | 71 |
CSS 语法
counter-set: none|counter-name number|initial|inherit;
属性值
值 | 描述 |
---|---|
none | 默认值。不执行任何计数器设置 |
counter-name number | 要设置的计数器名称以及在选择器每次出现时设置计数器的值。默认的number值为 0 |
initial | 将此属性设置为其默认值。阅读关于initial |
inherit | 从其父元素继承此属性。阅读关于inherit |
更多示例
示例
创建一个计数器(“my-counter”),将其设置为 5,并为 <h2> 选择器的每次出现减少一
body {
/* 将“my-counter”设置为 5 */
counter-set: my-counter 5;
}
h2::before {
/* 减少“my-counter” 1 */
counter-increment: my-counter -1;
content: "Section " counter(my-counter) ". ";
}
自己动手试一试 »
示例
对章节和子章节进行编号,例如“第 10 章:”、“10.1”、“10.2”等。
body {
/* 将“section”设置为 9 */
counter-set: section 9;
}
h1 {
/* 将 "subsection" 设置为 0 */
counter-set: subsection 0;
}
h1::before {
/* 增加“section” by 1 */
counter-increment: section;
content: "Section " counter(section) ": ";
}
h2::before {
/* 增加“subsection” by 1 */
counter-increment: subsection;
content: counter(section) "." counter(subsection) " ";
}
自己动手试一试 »
示例
创建计数器,将其设置为 9,并为 <h2> 选择器的每次出现增加一(使用罗马数字)
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 参考:::before 伪元素
CSS 参考:::after 伪元素
CSS 参考:content 属性
CSS 参考:counter-increment 属性
CSS 函数:counter() 函数