css counter-increment unwanted reset when skipping :before

人盡茶涼 提交于 2019-12-05 06:43:28

As per your CSS code for the counter, the value of h5 counter should be reset whenever you encounter an h4 tag.

body {counter-reset: h3}
h3 {counter-reset: h4}
h4 {counter-reset: h5} /* this one */

Because of the above code, when the browser encounters the h4 tag with no class (and content as No Counter) the counter value of h5 counter gets reset back to 0. This is the reason why instead of 1.1.3 you had got the value as 1.1.1

<h5 class="count">: should be : 1.1.2</h5>
<h4>No counter</h4> <!-- This line would cause h5 counter to reset -->
<h5 class="count">: should be : 1.1.3</span></h5>

If my understanding of your question is correct, what you actually need is to reset the counter only when the heading tags have class="count". Hence, modifying the counter-reset CSS code like below should solve the problem.

h3.count {counter-reset: h4}
h4.count {counter-reset: h5}

body {
  counter-reset: h3
}
h3.count {
  counter-reset: h4
}
h4.count {
  counter-reset: h5
}
h3.count:before {
  counter-increment: h3;
  content: counter(h3)". "
}
h4.count:before {
  counter-increment: h4;
  content: counter(h3)"." counter(h4)". "
}
h5.count:before {
  counter-increment: h5;
  content: counter(h3)"." counter(h4)"." counter(h5)". "
}
h3:before,
h4:before,
h5:before {
  content: "";
  counter-increment: none
}
<h3 class="count">: should be : 1</h3>
<h4 class="count">: should be : 1.1</h4>
<h5 class="count">: should be : 1.1.1</h5>
<h5>No counter</h5>
<h5 class="count">: should be : 1.1.2</h5>
<h4>No counter</h4>
<h5 class="count">: should be : <span style="color: #ff0000">1.1.3</span></h5>
<h5>No counter</h5>
<h5 class="count">: should be : <span style="color: #ff0000">1.1.4</span></h5>
<h4 class="count">: should be : 1.2</h4>

<h3>No counter</h3>
<h4 class="count">: should be : <span style="color: #ff0000">1.3</span></h4>
<h5 class="count">: should be : <span style="color: #ff0000">1.3.1</span></h5>
<h5>No counter</h5>
<h5 class="count">: should be : <span style="color: #ff0000">1.3.2</span></h5>
<h4>No counter</h4>
<h5 class="count">: should be : <span style="color: #ff0000">1.3.3</span></h5>
<h5>No counter</h5>
<h5 class="count">: should be : <span style="color: #ff0000">1.3.4</span></h5>
<h4 class="count">: should be : <span style="color: #ff0000">1.4</span></h4>

<h3 class="count">: should be : 2</h3>
<h5 class="count">: should be : 2.0.1</h5>
<h4 class="count">: should be : 2.1</h4>
<h5 class="count">: should be : 2.1.1</h5>
<h5>No counter</h5>
<h5 class="count">: should be : 2.1.2</h5>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!