3

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

MWE

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

  h2.heading::before {
    counter-increment: firstCounter;
    content: counter(firstCounter)"\00a0";
  }

  h3.issue::before {
    counter-increment: secondCounter;
    content: counter(secondCounter)"\00a0";
  }
  </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 中交换标签counter-reset下的顺序body会导致相同的问题,但与受影响的标题相反。

CodePen 链接

4

1 回答 1

5

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

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

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

body {
  counter-reset: firstCounter secondCounter;
}

名称:反增量

价值: [ ?]+ | 没有任何

<custom-ident> <integer>?

元素改变其上一个或多个计数器的值。如果元素上当前没有给定名称的计数器,则该元素创建一个具有给定名称的新计数器,其起始值为 0(尽管它可能会立即将该值设置或增加为不同的值)。

body {
  counter-reset: firstCounter secondCounter;
}

h2.heading::before {
  counter-increment: firstCounter;
  content: counter(firstCounter)"\00a0";
}

h3.issue::before {
  counter-increment: secondCounter;
  content: counter(secondCounter)"\00a0";
}

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

参考:

于 2018-08-26T03:29:26.810 回答