Home  >  Article  >  Web Front-end  >  What is the difference between CSS first-child and nth-child

What is the difference between CSS first-child and nth-child

藏色散人
藏色散人Original
2021-01-07 09:12:332857browse

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.

What is the difference between CSS first-child and nth-child

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 select25edfb22a4f469ecb59f1190150159c6l1bed06894275b65c1ab86501b08a632eb ul>li:first-child

To select25edfb22a4f469ecb59f1190150159c6l2bed06894275b65c1ab86501b08a632eb ul>li:nth-child(2)

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Is vue.js just node?Next article:Is vue.js just node?