CSS 嵌套在 div 中的标题计数器

CSS counters for headings nested in div

我 运行 遇到了一个 CSS 我自己无法解决的问题。

这很简单:CSS 计数器适用于没有 div 的标题,但不适用于 div 中的标题。

看下面的例子...

这个有效

h1 {
  counter-reset: h2;
}

h2 {
  counter-reset: h3;
}

h3 {
  counter-reset: h4;
}

h2::before {
    counter-increment: h2;
    content: counter(h2) ". ";
}

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

h4::before {
    counter-increment: h4;
    content: counter(h2) "." counter(h3) "." counter(h4) ". ";
}
<h1>Title</h1>

<h2>Section 1</h2>

<h2>Section 2</h2>

<h3>Subsection 1</h3>

<h3>Subsection 2</h3>

<h4>Subsubsection 1</h4>

<h4>Subsubsection 2</h4>

<h2>Section 3</h2>

这不起作用(算作有效)

h1 {
  counter-reset: h2;
}

h2 {
  counter-reset: h3;
}

h3 {
  counter-reset: h4;
}

h2::before {
    counter-increment: h2;
    content: counter(h2) ". ";
}

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

h4::before {
    counter-increment: h4;
    content: counter(h2) "." counter(h3) "." counter(h4) ". ";
}
<h1>Title</h1>

<div><h2>Section 1</h2></div> <!-- correct: 1. -->

<div><h2>Section 2</h2></div> <!-- correct: 2. -->

<div><h3>Subsection 1</h3></div> <!-- correct: 2.1. -->

<div><h3>Subsection 2</h3></div> <!-- wrong: 2.1. instead of 2.2 -->

<div><h4>Subsubsection 1</h4></div> <!-- wrong: 2.0.1 instead of 2.2.1 -->

<div><h4>Subsubsection 2</h4></div> <!-- wrong: 2.0.1 instead of 2.2.2 -->

<div><h2>Section 3</h2></div> <!-- correct: 3. -->

也许有人知道这个问题的解决方法并且可以解释为什么会这样。

非常感谢您的帮助。

如果我们给 div 一个 class 名称并将 counter-reset 切换为这些 class 就可以了。

h1 {
  counter-reset: h2;
}

.h2 {
  counter-reset: h3;
}

.h3 {
  counter-reset: h4;
}

h2::before {
    counter-increment: h2;
    content: counter(h2) ". ";
}

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

h4::before {
    counter-increment: h4;
    content: counter(h2) "." counter(h3) "." counter(h4) ". ";
}
<h1>Title</h1>

<div class="h2"><h2>Section 1</h2></div>

<div class="h2"><h2>Section 2</h2></div>

<div class="h3"><h3>Subsection 1</h3></div>

<div class="h3"><h3>Subsection 2</h3></div>

<div class="h4"><h4>Subsubsection 1</h4></div>

<div class="h4"><h4>Subsubsection 2</h4></div>

<div class="h3"><h2>Section 3</h2></div>