4

我正在尝试做这样的事情:

<h2>1.1 Bananas</h2>
<h3>1.1.1 </h3>
<h3>1.1.2 </h3>
<h3>1.1.3 </h3>

<h2>1.1 Apples</h2>
<h3>1.1.1 </h3>
<h3>1.1.2 </h3>
<h3>1.1.3 </h3>

<h2>1.1 Oranges</h2>
<h3>1.1.1</h3>
<h3>1.1.2</h3>
<h3>1.1.3</h3>

注意数字系列是如何重复的。

我可以通过 CSS 进行自动编号 - 但我不知道是否有办法重复编号系列。

4

1 回答 1

8

一种方法是使用 CSScounters并在每次h2遇到 a 时重置它们,如下面的代码片段所示。

每次遇到元素时,选择器中的counter-reset属性都会将计数器h2的值设置h2为 1,将计数器的值设置为 0(默认值)。h3h2

每次遇到元素时,选择器中的counter-increment属性都会增加计数器h3的值。h3h3

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);
}
于 2015-06-11T17:08:12.190 回答