CSS 计数器不递增

CSS counter not incrementing

我的示例中的 CSS 计数器不会递增,尽管我已指定它这样做。我在这里阅读了一些关于可能导致此问题的元素的嵌套级别的问题,但就我而言,所有元素都处于同一级别。

MWE

<!DOCTYPE html>
<head>
  <style>
  body {
    counter-reset: firstCounter;
    counter-reset: secondCounter;
  }

  h2.heading::before {
    counter-increment: firstCounter;
    content: counter(firstCounter)"[=11=]a0";
  }

  h3.issue::before {
    counter-increment: secondCounter;
    content: counter(secondCounter)"[=11=]a0";
  }
  </style>
</head>

<body>
  <h1>The Book</h1>

  <h2 class="heading">First Heading</h2>
    <h3 class="issue">The Issue of Drinking</h3>
    <h3 class="issue">The Issue of Drinking Too Much</h3>

  <h2 class="heading">Second Heading</h2>
    <h3 class="issue">The Issue of Driving</h3>
    <h3 class="issue">The Issue of Drunk Driving</h3>

</body>
</html>

结果

标题“第二个标题”的计数器需要为“2”。在 CSS 中的 body 标签下交换 counter-reset 的顺序会导致同样的问题,但相反的是受影响的标题。

CodePen Link

问题是counter-increment属性的重复定义:

body {
  counter-reset: firstCounter;
  counter-reset: secondCounter;
}

第二个定义覆盖第一个;要增加多个计数器,您只需使用白色 space 分隔的这些计数器列表:

body {
  counter-reset: firstCounter secondCounter;
}

Name: counter-increment

Value: [ ? ]+ | none

<custom-ident> <integer>?

The element alters the value of one or more counters on it. If there is not currently a counter of the given name on the element, the element creates a new counter of the given name with a starting value of 0 (though it may then immediately set or increment that value to something different).

body {
  counter-reset: firstCounter secondCounter;
}

h2.heading::before {
  counter-increment: firstCounter;
  content: counter(firstCounter)"[=12=]a0";
}

h3.issue::before {
  counter-increment: secondCounter;
  content: counter(secondCounter)"[=12=]a0";
}

/* irrelevant, just for the sake of easier visuals in the answer: */

h2 {
  border-top: 2px solid #aaa;
}

h3 {
  margin-left: 2em;
}
<h1>The Book</h1>

<h2 class="heading">First Heading</h2>
<h3 class="issue">The Issue of Drinking</h3>
<h3 class="issue">The Issue of Drinking Too Much</h3>

<h2 class="heading">Second Heading</h2>
<h3 class="issue">The Issue of Driving</h3>
<h3 class="issue">The Issue of Drunk Driving</h3>

参考: