Repeated series of number via CSS

眉间皱痕 提交于 2019-12-06 05:06:27

问题


I'm trying to do something like this:

<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>

Notice how the number series repeats.

I can do autonumbering via CSS - but I can't figure out if there's a way to repeat the numbered series.


回答1:


One way would to be use CSS counters and reset them every time a h2 is encountered like in below snippet.

The counter-reset property within the h2 selector sets the value of the h2 counter to 1 and that of the h3 counter to 0 (default) everytime a h2 element is encountered.

The counter-increment property within the h3 selector increments the value of the h3 counter everytime a h3 element is encountered.

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) -->

Actually, you don't even need the h2 counter for your case because the value is always 1. So even the below in CSS would suffice:

h2 {
  counter-reset: h3 0;
}
h2:before {
  content: "1.1";
}
h3 {
  counter-increment: h3;
}
h3:before {
  content: "1.1." counter(h3);
}


来源:https://stackoverflow.com/questions/30787024/repeated-series-of-number-via-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!