The difference between CSS first-child and nth-child: 1. first-child is a pseudo-class selector, which means matching the first child element of the parent element; 2. nth-child means matching the nth child element of the parent element child elements.
The operating environment of this tutorial: windows7 system, css3 version, Dell G3 computer.
Recommended: "css video tutorial"
first-child
E: first-child is a pseudo-class selector ,
Matches the first child element of the parent element E
It can be seen from the description that E is the first child element you want to select, not the parent element. At first, I mistakenly thought that E:first-child was the first child element of E.
:nth-child(n)
Matches the nth child element E
E of the parent element, which is also a child element, and only Can match the nth child element under the parent element. n starts counting from 1
<ul> <li>l1</li> <li>l2</li> <li>l3</li> </ul>
To select
To select
<div> <h1>h1</h1> <p>p1</p> <p>p2</p> <p>p3</p> </div>
At this time, select the first p element, and an error will occur when applying p:first-child, because the parent element of p is div, and for div , its first child element is not p, but h1, so if the selector p:first-child, an error will occur.
Similarly, E:last-child``E:only-child is the same as above. The E element must be the last child element or the only child element of its parent element
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of What is the difference between CSS first-child and nth-child. For more information, please follow other related articles on the PHP Chinese website!