我想用CSS嵌套两个不同的编号,以便获得如下所示的自动编号:
1 Section1
1-1 SubSection1
1-2 SubSection1
2 Section2
2-1 SubSection2
2-2 SubSection2
这是我要实现的目标:
<head>
<style>
body
{
counter-reset: sectioncount;
}
h1:before
{
counter-increment: sectioncount 1;
counter-reset: subsectioncount;
content: counter(sectioncount) " ";
}
h2:before
{
counter-increment: subsectioncount 1;
content: counter(sectioncount) "-" counter(subsectioncount) " ";
}
</style>
</head>
<body>
<h1>Section1</h1>
<h2>SubSection 1</h2>
<h2>SubSection 2</h2>
<h1>Section2</h1>
<h2>SubSection 1</h2>
<h2>SubSection 2</h2>
</body>
,但小节计数器不增加。我不知道为什么以及如何解决此问题。问题是:在CSS中实现此目标的正确方法是什么?
答案 0 :(得分:4)
说实话,我不知道为什么,但是在这种情况下,为主机元素(不是伪元素)设置计数器可以解决您的问题:
body {
counter-reset: sectioncount;
counter-reset: subsectioncount;
}
h1 {
counter-increment: sectioncount 1;
counter-reset: subsectioncount;
}
h1:before {
content: counter(sectioncount) " ";
}
h2 {
counter-increment: subsectioncount 1;
}
h2:before {
content: counter(sectioncount) "-" counter(subsectioncount) " ";
}
<h1>Section1</h1>
<h2>SubSection 1</h2>
<h2>SubSection 2</h2>
<h1>Section2</h1>
<h2>SubSection 1</h2>
<h2>SubSection 2</h2>
答案 1 :(得分:3)
您可以使用CSS计数器执行此操作:https://jsfiddle.net/tfechswg/3/
这里有个例子:
ol {
counter-reset: item;
}
li {
display: block;
}
li:before {
content: counters(item, "-") " ";
counter-increment: item;
}
<ol>
<li>Section 1
<ol>
<li>sub section</li>
<li>sub section</li>
<li>sub section</li>
</ol>
</li>
<li>li section</li>
<li>li section
<ol>
<li>sub section</li>
<li>sub section</li>
<li>sub section</li>
</ol>
</li>
</ol>