I've a div
and inside the div
there is multiple p
tags. I need to number them using css. The count of p
tag may vary.
Using :nth-child()
and ::before
I can do something like this
div p:first-child::before {
content: '1 '
}
div p:nth-child(2)::before {
content: '2 '
}
div p:nth-child(3)::before {
content: '3 '
}
div p:nth-child(4)::before {
content: '4 '
}
div p:nth-child(5)::before {
content: '5 '
}
<div>
<p>abc</p>
<p>abc</p>
<p>abc</p>
<p>abc</p>
<p>abc</p>
</div>
If there is large amount of elements how can I implement it. Is there any way to child number in css inside :nth-child()
, something like this.
div p:nth-child(n)::before {
content: n
}
where n
is the child number. I know numbering can done using list, but I need to know is there any way to get child num inside the css selector.
The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.
formula (an + b) nth-child(3n) would affect every third child element. nth-child(3n+1) would apply to every third element starting from the first one.
The CSS child selector has two selectors separated by a > symbol. The first selector indicates the parent element. The second selector indicates the child element CSS will style.
You can use CSS counters by using ::before
(:before
for IE8) and counter-reset/increment
div {
counter-reset: number;
}
p {
counter-increment: number;
}
p::before {
content: counter(number)" ";
}
<div>
<p>abc</p>
<p>abc</p>
<p>abc</p>
<p>abc</p>
<p>abc</p>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With