如何阻止<div>标签干扰多个标题的计数器?

时间:2017-01-16 10:35:55

标签: html css css-counter

这是How do I stop <div> tags interfering with counters?

的扩展

接受的答案解决了一个标题级别的问题(即问题中的H1),但是如果有多个标题级别(见下文)则不能解决问题

body {
  counter-reset: h1 h2 h3 h4;
}
h1 {
  counter-reset: h2 h3 h4;
}
h2 {
  counter-reset: h3 h4;
}
h3 {
  counter-reset: h4;
}
h1:before {
  counter-increment: h1;
  content: counter(h1)"  ";
}
h2:before {
  counter-increment: h2;
  content: counter(h1)"." counter(h2)"  ";
}
h3:before {
  counter-increment: h3;
  content: counter(h1)"."counter(h2)"."counter(h3)"  ";
}
h4:before {
  counter-increment: h4;
  content: counter(h1)"."counter(h2)"."counter(h3)"."counter(h4)"  ";
}
div:before {
  content: counter(h1)"."counter(h2)"."counter(h3)"."counter(h4)"  ";
}
<div>
  div
  <h1>H1</h1>
  <h2>H2</h2> 
  <h3>H3</h3>
  <h4>H4</h4>
  <h4>H4</h4>
  <h4>H4</h4>
</div>
<div>
  div
  <h4>H4</h4>
  <h4>H4</h4>

</div>
<div>
  div
  <h3>T1</h3>
  <h3>T1</h3>	
</div>
从上面可以看出剪切不是所有的计数器都是在div之间继承的。有办法解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

我的解决方案:

<强>取代:

h1{counter-reset: h2 h3 h4;}
h2{counter-reset: h3 h4;}
h3{counter-reset: h4;}

<强>与

h1{counter-reset: h2 initial h3 initial h4 initial;}
h2{counter-reset: h3 initial h4 initial;}
h3{counter-reset: h4 initial;}

body {
  counter-reset: h1 h2 h3 h4;
}
h1 {
  counter-reset: h2 initial h3 initial h4 initial;
}
h2 {
  counter-reset: h3 initial h4 initial;
}
h3 {
  counter-reset: h4 initial;
}
h1:before {
  counter-increment: h1;
  content: counter(h1)"  ";
}
h2:before {
  counter-increment: h2;
  content: counter(h1)"." counter(h2)"  ";
}
h3:before {
  counter-increment: h3;
  content: counter(h1)"."counter(h2)"."counter(h3)"  ";
}
h4:before {
  counter-increment: h4;
  content: counter(h1)"."counter(h2)"."counter(h3)"."counter(h4)"  ";
}
div:before {
  content: counter(h1)"."counter(h2)"."counter(h3)"."counter(h4)"  ";
}
<div>
  div
  <h1>H1</h1>
  <h2>H2</h2> 
  <h3>H3</h3>
  <h4>H4</h4>
  <h4>H4</h4>
  <h4>H4</h4>
</div>
<div>
  div
  <h4>H4</h4>
  <h4>H4</h4>

</div>
<div>
  div
  <h3>T1</h3>
  <h3>T1</h3>	
</div>