How to Select the First Child of a Class in CSS?

To select the first child of a class, you can use the class selector in combination with the :first-child selector. The :first-child selector allows you to select only the first child of its parent element.

Let’s say we have 4 paragraphs each with class="highlight" and we want to select only the first child of the highlight class:

<p class="highlight">This is the first child</p>
<p class="highlight">This is the second child</p>
<p class="highlight">This is the third child</p>
<p class="highlight">This is the fourth child</p>

To select only the first child of the highlight class, we have to combine the highlight class with the :first-child selector.

This is how you can do it in your CSS file:

/*Select the first child of a class*/
.highlight:first-child{
    background-color: yellow;
}

This will be the output after applying the above styles:


Method 2: Using the :nth-child() selector

You can also use the :nth-child() selector to select the first child of a class. To do that you have to pass an integer value 1 into the :nth-child() selector.

Here, 1 denotes that we want to select only that child which is the first child of its parent element.

This is how you can do it:

/*Select the first child of the highlight class*/
.highlight:nth-child(1){
    background-color: yellow;
}

Similarly, you can pass other values such as 2, 3, 4, etc. to select the second, third or fourth child of the highlight class.

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.