Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS numbering using nth-child

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.

like image 445
Pranav C Balan Avatar asked May 22 '16 10:05

Pranav C Balan


People also ask

What does nth child do CSS?

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.

How do I select all 3 children in CSS?

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.

How do I select a specific child in CSS?

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.


1 Answers

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>
like image 126
dippas Avatar answered Oct 05 '22 01:10

dippas