qazwsx
qazwsx

Reputation: 26868

In CSS, how to create automatic section numbering only when there are multiple sections?

In CSS, how to create automatic section numbering only when there are multiple sections? I learned that one can create automatica numbering in front of sections by using 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) " ";
}

which generate something like

1.1 XXX

for HTML

<h3>XXX</h3>

and something like

1.1 XXX

...

1.2 XXX2

for HTML

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

But I want this numbering to be generated of course only when there are multiple <h3> tags in the HTML. Is it possible to achieve that?

Upvotes: 2

Views: 223

Answers (1)

Luizgrs
Luizgrs

Reputation: 4873

If the <h3> tags are all under the same parent you can go with :not and :only-of-type selectors:

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

The :only-of-type will only match elements which have no other sibling of the same tag name. So it'll match only <h3> which are the only <h3> of their parent.

The :not negates it, making the selector to match only <h3> tags when its parent have more than one <h3> child.

It reads like "Match all H3 which are not the only H3 child of its parent".

Upvotes: 3

Related Questions