HTML 标题编号意外重置

mrg*_*gou 2 html css

我希望简单 HTML 网页中的标题能够按层次编号。因此我有:

body {
  counter-reset: h1counter;
}

h1:before {
  content: counter(h1counter) ".\0000a0\0000a0";
  counter-increment: h1counter;
  counter-reset: h2counter;
}

h2:before {
  content: counter(h1counter) "." counter(h2counter) ".\0000a0\0000a0";
  counter-increment: h2counter;
}
Run Code Online (Sandbox Code Playgroud)
<h1>Section 1</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>
<h1>Section 2</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>
<h1>Section 3</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>
Run Code Online (Sandbox Code Playgroud)

但这显示如下:

1.  Section 1
1.1.  Subsection 1
1.1.  Subsection 2
2.  Section 2
2.1.  Subsection 1
2.1.  Subsection 2
Section 3
3.1.  Subsection 1
3.1.  Subsection 2
Run Code Online (Sandbox Code Playgroud)

显然,第 2 小节 标题的第二个编号数字<h2>应该是 2,但它不会增加(就好像counter-increment: h2counter;没有执行一样),就像标题一样<h1>

我错过了什么?

小智 6

您应该将“h2counter Reset”行移动到单个 h1 选择器中。样式的最终结果应该是这样的:

body {
    counter-reset: h1counter;
}
h1 {
    counter-reset: h2counter;
}
h1:before {
    content: counter(h1counter) ".\0000a0\0000a0";
    counter-increment: h1counter;
}
h2:before {
    content: counter(h1counter) "." counter(h2counter) ".\0000a0\0000a0";
    counter-increment: h2counter;
}
Run Code Online (Sandbox Code Playgroud)
<h1>Section 1</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>
<h1>Section 2</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>
<h1>Section 3</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>
Run Code Online (Sandbox Code Playgroud)