css实现各级标题自动编号
在CSS中,可以使用counter-increment
和counter()
来实现各级标题的自动编号。以下是一个简单的例子,展示了如何为h1
到h3
标题自动添加编号:
body {
counter-reset: section;
}
h1 {
counter-increment: section;
counter-reset: subsection;
}
h1::before {
content: counter(section) ". ";
}
h2 {
counter-increment: subsection;
counter-reset: subsubsection;
}
h2::before {
content: counter(section) "." counter(subsection) " ";
}
h3 {
counter-increment: subsubsection;
}
h3::before {
content: counter(section) "." counter(subsection) "." counter(subsubsection) " ";
}
在这个例子中,counter-reset
属性用于重置计数器。每个h1
标签都会重置section
计数器,并且在每个h1
元素前添加编号。h2
标签会重置subsection
计数器,并在其前面添加section.subsection
编号。类似地,h3
标签会重置subsubsection
计数器,并在其前面添加section.subsection.subsubsection
编号。
在HTML中,可以这样使用:
<h1>这是第一级标题</h1>
<h2>这是第二级标题</h2>
<h3>这是第三级标题</h3>
当渲染这些元素时,它们将自动带有编号。
评论已关闭