Visitar URL original
[css] 第54天 css3的:nth-child和:nth-of-type的区别是什么? · Issue #212 · haizlin/fe-interview · GitHub
Skip to content

[css] 第54天 css3的:nth-child和:nth-of-type的区别是什么? #212

Description

@haizhilin2013

第54天 css3的:nth-child和:nth-of-type的区别是什么?

Activity

  1. xiangshuo1992 commented on Jun 10, 2019

    @xiangshuo1992
    Contributor

    :nth-child(n) 选择器匹配属于其父元素的第 N 个子元素,不论元素的类型。
    :nth-of-type(n) 选择器匹配属于父元素的特定类型的第 N 个子元素。
    n 可以是数字、关键词或公式。

  2. dugufck666 commented on Oct 25, 2021

    @dugufck666

    p:nth-child(n),匹配所有p标签的父元素的第n个元素,并且这个元素是p标签,如果这个元素不是p标签,那么就不会匹配到
    p:nth-of-type(n),匹配所有p标签的父元素的第n个p标签元素

  3. never123450 commented on Sep 15, 2023

    @never123450

    在 CSS3 中, :nth-child 和 :nth-of-type 是用于选择特定位置元素的伪类选择器,它们之间有一些区别。

    1. :nth-child 选择器:它选择在其父元素中的特定位置的所有子元素,无论其元素类型如何。语法为 :nth-child(an+b) ,其中 a 和 b 是整数值,用于计算选择的位置。例如, :nth-child(2n+1) 选择所有奇数位置的子元素。

    2. :nth-of-type 选择器:它选择在其父元素中的特定位置的相同类型的子元素。语法为 :nth-of-type(an+b) ,其中 a 和 b 是整数值,用于计算选择的位置。例如, :nth-of-type(2n+1) 选择所有奇数位置的相同类型的子元素。

    区别:

    • :nth-child 选择器会选择其父元素下的所有子元素,无论其元素类型如何。而 :nth-of-type 选择器只会选择相同类型的子元素。
    • 例如,对于以下 HTML 结构:
    <div>
       <p>Paragraph 1</p>
       <span>Span 1</span>
       <p>Paragraph 2</p>
       <span>Span 2</span>
     </div>
    • 使用 :nth-child(2) 选择器将选择第二个子元素,即 <span>Span 1</span> 。
      • 使用 :nth-of-type(2) 选择器将选择第二个相同类型的子元素,即 <span>Span 2</span> 。

    因此,根据选择的需求,您可以选择使用 :nth-child 还是 :nth-of-type 来选择特定位置的元素。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions