在CSS中,如何在有多个部分时创建自动部分编号?

时间:2014-10-11 16:42:02

标签: html css automatic-properties

在CSS中,如果只有多个部分时如何创建自动章节编号?我了解到可以使用CSS

在部分前面创建自动编号
body { counter-reset: section }
h2 { counter-reset: sub-section }
h3 { counter-reset: composite }
h4 { counter-reset: detail }

h2:before{
    counter-increment: section;
    content: counter(section) " ";
}
h3:before{
    counter-increment: sub-section;
    content: counter(section) "." counter(sub-section) " ";
}
h4:before{
    counter-increment: composite;
    content: counter(section) "." counter(sub-section) "." counter(composite) " ";
}
h5:before{
    counter-increment: detail;
    content: counter(section) "." counter(sub-section) "." counter(composite) "." counter(detail) " ";
}

生成类似

的内容
1.1 XXX

for HTML

<h3>XXX</h3>

等等

1.1 XXX

...

1.2 XXX2

for HTML

<h3>XXX</h3>
...
<h3>XXX2</h3>

但我希望只有当HTML中有多个<h3>标记时才会生成此编号。是否有可能实现这一目标?

1 个答案:

答案 0 :(得分:2)

如果<h3>标记都在同一个父级下,您可以使用:not:only-of-type选择器:

h3:not(:only-of-type)::before{
    counter-increment: sub-section;
    content: counter(section) "." counter(sub-section) " ";
}

:only-of-type只匹配没有相同标签名称的其他兄弟的元素。因此,它仅匹配<h3>,这是其父级的唯一<h3>

:not对其进行否定,使得选择器只有<h3>个标签时,其父级有多个<h3>子标记。

它类似于&#34;匹配所有H3,它们不是其父母的唯一H3子女&#34;。