:nth-child() unexpected result

I am using coding of the form,

<div class="aaa">
          <p>text</p>
          <p>text</p>
          <p>text</p>
           <p>text</p>
</div>

and I wanted a different style for each paragraph so I used the following CSS:

.aa p:nth-child(1){style1;}
.aa p:nth-child(2){style2;}
.aa p:nth-child(3){style3;}
.aa p:nth-child(4){style;}

and this worked fine but then I decided to add an <h2> tag between paragraphs 2 and 3 and I found that paragraph 3 was styled as p:nth-child(4). When I changed the p:nth-child(3) to p:nth-child(4) and p:nth-child(4) to p:nth-child(5) it was then O.K.
Can someone please explain why, please?

EDIT
This post has been reformatted by enclosing the code block in 3 backticks
```
on their own lines.

That code can’t work as you presented it, because your div has a class of .aaa, not .aa. (Presumably that’s a typo?)

Anyhow, nth-child means exactly that. The Ps and H2 are all children of the div. The H2 is the third child.

What you are looking for here is the nth-of-type property, rather than nth-child. That will just sift through the Ps, because they are all of one type.

Many thanks for that explanation.
It was a typo by the way.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.