How to Select the Second Paragraph in a div using CSS?

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:

Select the Second Paragraph in a div using CSS

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:

Select even and odd paragraphs inside a div using CSS

Thanks for reading.


Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.