To select the second paragraph in a div element, you can use the :nth-child(N)
selector. The :nth-child(N) selector allows you to select the nth child of its parent element.
So, if you want to select the second paragraph, you have to pass the value of N as 2, i.e. p:nth-child(2)
. Similarly, to select the third child, the value of N will be 3, i.e. p:nth-child(3)
and so on.
Let’s say we have a div element which has several paragraphs inside of it:
<div> <p>First paragraph</p> <p>Second paragraph</p> <p>Third paragraph</p> <p>Fourth paragraph</p> </div>
Now, if we want to select the second paragraph of this div, we can simply pass the value of N as 2 into the :nth-child()
selector:
/*Select only the second paragraph*/ div p:nth-child(2){ background-color: yellow; }
The above CSS code will highlight only the second paragraph:
You can also select those paragraphs which are at even and odd positions inside of the div. In that case, you have to simply pass the even
and odd
keywords into the :nth-child()
selector.
See the below CSS code:
/*Select the odd paragraphs*/ div p:nth-child(odd){ background-color: yellow; } /*Select the even paragraphs*/ div p:nth-child(even){ background-color: pink; }
The above CSS code will highlight the odd paragraphs with yellow background and even paragraphs with pink background:
Thanks for reading.