Search code examples
htmlcsscss-selectorspseudo-class

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.


Solution

  • 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>