CSS nth-of-type和nth-child详解

4,053 阅读1分钟

nth-of-type 匹配指定的第N个出现的元素,同时要满足匹配的规则,且和标签类型有关。与nth-child不同的是,nth-child匹配的是该层级中元素所在的位置,nth-of-type匹配的是相同类型标签出现的顺序。注意,nth-child和nth-of-type都是默认是匹配多层元素的。

举例说明

DOM结构

 <div class="wrapper">
  <p class="red">p1</p>
  <p class="red">p2</p>
  <p class="red">p3</p>
  <div class="red">div1</div>
  <div class="red">div2</div>
</div>

指定特定标签类型

// 只匹配首个p标签
p:nth-of-type(1) {
    color: red;
}

不指定类型,匹配所有

// 既包括wrapper下首个子元素,也包括pdiv下首个子元素(文本标签)。
:nth-of-type(1) {
    color: red;
 }

指定父元素,不指定类型

// 匹配wrapper元素下,相同类型元素组的第一个,即第一个p标签和第一个div标签
.wrapper :nth-of-type(1) {
    color: red;
 }

指定class,不指定类型

// 匹配同一组类型中第一个元素,且该元素class包含red
.red:nth-of-type(1) {
    color: red;
 }

同样的样式,改一下DOM结构看看

 <div class="wrapper">
 <!--第一个p元素class不包含red,匹配不到了-->
  <p>p1</p>
  <p class="red">p2</p>
  <p class="red">p3</p>
  <div class="red">div1</div>
  <div class="red">div2</div>
</div>

nth-of-type和nth-child对子元素也能生效

  <div class="wrapper">
    <div class="red">
      1
      <div>11</div>
      <div>12</div>
    </div>
    <div class="red">
      2
      <div>21</div>
      <div>22</div>
    </div>
    <div class="red">
      3
      <div>31</div>
      <div>32</div>
    </div>
  </div>
<style>
.wrapper :nth-child(2) {
  color:  red;
}
</style>

image.png 12和32是属于子元素第二个子元素,因此也能生效。 如果想要只对直接子元素第二个元素生效:

<style>
.wrapper > :nth-child(2) {
  color:  red;
}
</style>

image.png 以上规则nth-of-type同理。