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

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

藏色散人
Release: 2021-01-08 14:39:41
Original
2933 people have browsed it

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>
Copy after login

To select

  • l1
  • ul>li:first-child

    To select

  • l2
  • ul>li:nth-child(2)

    <div>
        <h1>h1</h1>
        <p>p1</p>
        <p>p2</p>
        <p>p3</p>
    </div>
    Copy after login

    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!

    Related labels:
    css
    source:php.cn
    Statement of this Website
    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
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template