Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 992
qazwsx Avatar asked Nov 25 '25 16:11

qazwsx


1 Answers

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".

like image 50
Luizgrs Avatar answered Nov 27 '25 07:11

Luizgrs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!