CSS 计数器
学习counter · 难度:进阶 · +15XP
CSS 计数器完全指南
CSS 计数器是一种自动编号机制,无需 JavaScript 即可为网页元素动态生成序号。它由 counter-reset、counter-increment 和 counter()/counters() 函数组成。
核心属性
| 属性/函数 | 作用 |
|---|---|
counter-reset | 初始化或重置计数器 |
counter-increment | 递增加计数器 |
counter() | 获取计数器当前值 |
counters() | 获取嵌套计数器的完整路径 |
基本使用流程
/* 步骤一:在父元素初始化计数器 */
.container {
counter-reset: my-counter;
/* my-counter 从 0 开始 */
}
/* 步骤二:在子元素上递增 */
.item {
counter-increment: my-counter;
/* 每个 .item 让 my-counter + 1 */
}
/* 步骤三:显示计数器值 */
.item::before {
content: counter(my-counter) ". ";
/* 输出:1. 2. 3. ... */
}
完整示例 — 自定义章节编号
<article>
<h2>CSS 基础</h2>
<h2>CSS 布局</h2>
<h2>CSS 动画</h2>
</article>
<style>
article {
counter-reset: chapter;
}
article h2 {
counter-increment: chapter;
}
article h2::before {
content: "第 " counter(chapter) " 章 ";
color: #2196F3;
font-weight: bold;
}
</style>
起始值与步长
/* 从 5 开始 */
.parent {
counter-reset: count 5; /* 初始值 5 */
}
.child {
counter-increment: count 2; /* 每次 +2 */
}
嵌套计数器
使用 counters() 函数处理多级嵌套,如目录编号:
<ol class="nested">
<li>第一章
<ol>
<li>第一节
<ol>
<li>知识点 A</li>
<li>知识点 B</li>
</ol>
</li>
<li>第二节</li>
</ol>
</li>
<li>第二章</li>
</ol>
<style>
.nested {
counter-reset: level1;
list-style: none;
}
.nested > li {
counter-increment: level1;
counter-reset: level2; /* 每个一级项重置二级 */
}
.nested > li::before {
content: counter(level1) ". ";
font-weight: bold;
}
.nested > li > ol {
counter-reset: level2;
list-style: none;
}
.nested > li > ol > li {
counter-increment: level2;
counter-reset: level3; /* 重置三级 */
}
.nested > li > ol > li::before {
content: counter(level1) "." counter(level2) " ";
}
.nested > li > ol > li > ol > li {
counter-increment: level3;
}
.nested > li > ol > li > ol > li::before {
content: counter(level1) "." counter(level2) "." counter(level3) " ";
}
</style>
counters() 简化嵌套
/* 使用 counters() 更简洁 */
.nested li::before {
content: counters(section, ".") " ";
/* 自动连接各级编号 */
}
计数器格式
可以指定计数器的列表样式类型:
counter(name, style)
/* 样式类型 */
::before { content: counter(step, upper-roman); } /* I, II, III... */
::before { content: counter(step, lower-alpha); } /* a, b, c... */
::before { content: counter(step, upper-alpha); } /* A, B, C... */
::before { content: counter(step, decimal-leading-zero); } /* 01, 02... */
::before { content: counter(step, cjk-ideographic); } /* 一, 二, 三... */
实际应用场景
- 自动目录编号:如 1.1, 1.2, 2.1 格式
- 有序列表定制:自定义序号样式和起始值
- 代码行号:自动为代码块添加行号
- 统计元素数量:在页脚显示"共 N 篇文章"
- 进度步骤条:多步骤表单的编号展示
显示总数
.container {
counter-reset: items;
}
.item {
counter-increment: items;
}
.summary::after {
content: "共 " counter(items) " 项";
}
CSS 计数器是纯 CSS 实现动态编号的强大工具,对于文档、教程、步骤引导等需要自动编号的场景尤为实用。