The difference between ":nth-child", ":first-child" and ":first-of-type" in CSS

Reference

CSS selector :nth-child :first-child :first-of-type

Detailed explanation

First, let's look at the following HTML sample code, through this code we will understand the usage of the three selectors one by one.

            <div id="divMain">
    <div>
        <p id="p1">p1</p>
        <div id="div1">div1</div>
        <p id="p2">p2</p>
    </div>
    <p id="p3">p3</p>
    <div id="div2">div2<div>
</div>
<style>
/*css1*/
#divMain div:nth-child(2) {
    color: blue;
}
/*css2*/
#divMain p:first-child {
    color: red;
}
/*css3*/
#divMain p:first-of-type {
    background-color: blue;
}
</style>
        

":Nth-child" explained in detail

The meaning of css1 in the above code is the second child element and the type is "div", so only div1 is selected. div1 is the second child element in the parent container and the type is "div". p3 is the second child element of the parent container, but it is not of type "div" so it is not selected. If we modify the style to remove the div in front of the selector, then p3 will also be selected.

":First-child" explained in detail

The meaning of css2 in the above code is the first child element and the type is p, so only p1 is selected. p1 is the first child element in the parent container and the type is "p". It is similar to the above ":nth-child". If you use ":nth-child" to pass the parameter to 1, the effect is exactly the same.

":First-of-type" explained in detail

The meaning of css3 in the above code is that the first type is a child element of "p". The difference here from the above two selectors is that the corresponding type is first found, and then the first element that matches the type is obtained. So the selected ones are p1 and p3. Both p1 and p3 are the first "p" elements in the parent container.