counter-reset 用于创建或重置计数器,通常在父元素上初始化,配合 counter-increment 实现自动编号。通过在多级结构中合理设置 counter-reset,可实现章节、小节等嵌套编号,如“1.1, 1.2, 2.1”,关键在于父级递增时重置子级计数器,确保编号独立。

counter-reset
counter-increment
在使用
counter-reset
counter-reset: <counter-name> <value>;
<counter-name>
<value>
<value>
举个例子,如果你想给一个文档的章节进行编号,你可能会在
body
section
counter-reset: chapter;
chapter
h2
counter-increment: chapter;
chapter
content: counter(chapter) ". ";
一个比较容易被忽视但非常强大的特性是,你可以在同一个
counter-reset
counter-reset: chapter 1 section 0;
立即学习“前端免费学习笔记(深入)”;
我个人觉得,
counter-reset
counter-reset
counter-reset
/* 示例:简单的章节编号 */
body {
counter-reset: chapter; /* 初始化一个名为 'chapter' 的计数器,默认值为0 */
}
h2::before {
counter-increment: chapter; /* 每次遇到h2,chapter计数器加1 */
content: "Chapter " counter(chapter) ". "; /* 显示章节号 */
font-weight: bold;
}
/* 示例:多级列表编号 */
.my-list {
counter-reset: item; /* 为整个列表初始化计数器 */
}
.my-list li {
counter-increment: item; /* 每个列表项递增 */
}
.my-list li::before {
content: counter(item) ". ";
font-weight: normal;
margin-right: 5px;
}counter-reset
这确实是
counter-reset
counter-reset
counter-increment
关键在于理解计数器的“作用域”和“层叠”行为。当你在一个父元素上设置
counter-reset: section;
h3
counter-increment: section;
section
counter-reset: subsection;
div
counter-reset: section;
我们来看一个常见的模式:章节-小节编号。
<section>
<h2>第一章</h2>
<p>这是第一章的内容。</p>
<section>
<h3>1.1 小节</h3>
<p>这是第一章第一小节的内容。</p>
</section>
<section>
<h3>1.2 小节</h3>
<p>这是第一章第二小节的内容。</p>
</section>
</section>
<section>
<h2>第二章</h2>
<p>这是第二章的内容。</p>
<section>
<h3>2.1 小节</h3>
<p>这是第二章第一小节的内容。</p>
</section>
</section>为了给这个结构编号,CSS 可以这样写:
body {
counter-reset: chapter; /* 全局初始化章节计数器 */
}
section h2::before {
counter-increment: chapter; /* 章节计数器递增 */
counter-reset: section; /* 每次新章节开始,小节计数器重置为0 */
content: counter(chapter) ". ";
font-weight: bold;
}
section h3::before {
counter-increment: section; /* 小节计数器递增 */
content: counter(chapter) "." counter(section) " "; /* 显示章节和小节号 */
font-weight: normal;
}这里,
section h2::before
counter-reset: section;
h2
section
counter-reset
counter-increment
这块内容我觉得挺重要的,因为我见过不少人在用计数器的时候踩坑。
常见误区:
counter-increment
counter-reset
counter-reset
counter-reset
ul
counter-reset: item;
li
counter-increment
item
li
counter-reset: item;
li
content: counter(name);
::before
::after
最佳实践:
body
body
h2
chapter
section
item
c1
c2
::before
::after
counter-reset
counter-increment
display
display: block
display: inline-block
counter-reset
counter-reset: chapter 1 section 0;
我觉得最重要的是,把计数器想象成一个变量。
counter-reset
counter-increment
counter-reset
除了传统的文档编号,
counter-reset
counter-reset
counter-increment
以上就是CSS中counter-reset如何使用?通过counter-reset初始化计数器以实现编号的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号