我试图在从CodeMirror标记编辑器呈现的HTML代码上使用CSS计数器编号标题。我已经在类似的主题上看到过陶的回答,但正如您在下面看到的,在我的示例中,每个标题都由一个单独的div包装,其中一个使它成为错误。
.wrapper {
counter-reset: a b c; /* ... */
}
h1.numbered {
counter-increment: a;
counter-reset: b;
}
h2.numbered {
counter-increment: b;
counter-reset: c;
}
/* ... */
h1.numbered::before {
content: counter(a) " ";
}
h2.numbered::before {
content: counter(a) "." counter(b) " ";
}
/* ... */<div class="wrapper">
<div><h1 class="numbered">Heading 1</h1></div>
<div><h2 class="numbered">Heading 1.1</h2></div>
<div><h2 class="numbered">Heading 1.2</h2></div>
<div><h1 class="numbered">Heading 2</h1></div>
<div><h2 class="numbered">Heading 2.1</h2></div>
<div><h2 class="numbered">Heading 2.2</h2></div>
</div>
我认为原因是计数器的启动范围(通过反重置),可能会阻止它们持有正确的值或遵循内部逻辑。
请务必让我知道,如果您可以想出任何解决方案,而不需要改变HTML结构。
发布于 2022-08-31 19:24:40
你必须“初始化”(重置)他们的共同祖先的两个计数器。然后,值将绑定到它,并在所有子程序中使用。要真正重置(实际上只是设置)子标题级别,您必须使用counter-set。
body { counter-reset: h1 h2; }
h1 {
counter-increment: h1;
counter-set: h2 0;
}
h2 {
counter-increment: h2;
}
h1::before { content: counter(h1) ' '; }
h2::before { content: counter(h1) '.' counter(h2) ' '; }<div><h1>Heading 1</h1></div>
<div><h2>Heading 1.1</h2></div>
<div><h2>Heading 1.2</h2></div>
<div><h1>Heading 2</h1></div>
<div><h2>Heading 2.1</h2></div>
<div><h2>Heading 2.2</h2></div>
counter-reset在后代和相邻的连续兄弟姐妹中创建新的“作用域”。counter-set设置值。
https://stackoverflow.com/questions/73560839
复制相似问题