一种方法是使用 CSScounters
并在每次h2
遇到 a 时重置它们,如下面的代码片段所示。
每次遇到元素时,选择器中的counter-reset
属性都会将计数器h2
的值设置h2
为 1,将计数器的值设置为 0(默认值)。h3
h2
每次遇到元素时,选择器中的counter-increment
属性都会增加计数器h3
的值。h3
h3
h2 {
counter-reset: h2 1 h3 0;
}
h2:before {
content: "1." counter(h2);
}
h3 {
counter-increment: h3;
}
h3:before {
content: "1." counter(h2)"." counter(h3);
}
<h2>Bananas</h2> <!-- h2 counter = 1, h3 counter = 0 -->
<h3></h3> <!-- h2 counter = 1, h3 counter = 1 (increment) -->
<h3></h3> <!-- h2 counter = 1, h3 counter = 2 (increment) -->
<h3></h3> <!-- h2 counter = 1, h3 counter = 3 (increment) -->
<h2>Apples</h2> <!-- h2 counter = 1 (reset), h3 counter = 0 (reset) -->
<h3></h3> <!-- h2 counter = 1, h3 counter = 1 (increment) -->
<h3></h3> <!-- h2 counter = 1, h3 counter = 2 (increment) -->
<h3></h3> <!-- h2 counter = 1, h3 counter = 3 (increment) -->
<h2>Oranges</h2> <!-- h2 counter = 1 (reset), h3 counter = 0 (reset) -->
<h3></h3> <!-- h2 counter = 1, h3 counter = 1 (increment) -->
<h3></h3> <!-- h2 counter = 1, h3 counter = 2 (increment) -->
<h3></h3> <!-- h2 counter = 1, h3 counter = 3 (increment) -->
实际上,您甚至不需要h2
针对您的情况使用计数器,因为该值始终为 1。所以即使 CSS 中的以下内容就足够了:
h2 {
counter-reset: h3 0;
}
h2:before {
content: "1.1";
}
h3 {
counter-increment: h3;
}
h3:before {
content: "1.1." counter(h3);
}