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

问题描述

我遇到了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 s一个类名,并将counter-reset切换到这些类,则它起作用。

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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...