美文网首页
深入理解nth-child和nth-of-type

深入理解nth-child和nth-of-type

作者: A郑家庆 | 来源:发表于2021-07-09 14:17 被阅读0次

定义

:nth-child(n)选择器匹配父元素中的第n个子元素,元素类型没有限制,n可以是数字或公式
:nth-of-type(n)选择器匹配同类型中的第n个同级兄弟元素,n可以是数字或公式

例子1:

<template>
    <section>
        <p>我是第1个p标签</p>
        <p>我是第2个p标签</p>  <!-- 希望这个变红 -->
    </section>
</template>
<style>
  p:nth-child(2) { color: red; }
  p:nth-of-type(2) { color: red; }
</style>

我们发现这两个样式表现一致

例子2

<template>
    <section>
        <span>打扰项</span>
        <p>我是第1个p标签</p>
        <p>我是第2个p标签</p>  <!-- 希望这个变红 -->
    </section>
</template>
<style>
  p:nth-child(2) { color: red; }
  p:nth-of-type(2) { color: red; }
</style>

我们发现这两者表现不一致,第一个标红的是p:nth-child(2),表示匹配父元素中的第2个子元素并且这个元素是p元素,第一个p元素正好符合所以标红,第二个标红的是p:nth-of-type(2),表示匹配同类型(p元素)中的第2个同级兄弟元素

例子3

<template>
    <section>
        <div>打扰项1</div>
        <span>打扰项2</span>
        <p>我是第1个p标签</p>
        <p>我是第2个p标签</p>  <!-- 希望这个变红 -->
    </section>
</template>
<style>
p:nth-child(2) { color: red; }
p:nth-of-type(2) { color: red; }
</style>

p:nth-child(2)发现父元素下的第二个元素是span不是p元素不符合条件所以没有标红,p:nth-of-type(2)找到同类型p元素的第二个p元素存在,所以可以标红

例子4

<template>
    <section>
        <div class="item">打扰项1</div>
        <span class="item">打扰项2</span>
        <p class="item">我是第1个p标签</p>
        <p class="item">我是第2个p标签</p>  <!-- 希望这个变红 -->
    </section>
</template>
<style>
.item:nth-child(2) { color: red; }
.item:nth-of-type(2) { color: red; }
</style>

.item:nth-child(2)寻找父元素下的第二个子元素并且class类名是item给它标红,.item:nth-of-type(2)寻找同类型元素(p元素)中的第2个同级兄弟元素给它标红

例子5

<template>
    <section>
        <div class="item">打扰项1</div>
        <div class="item">打扰项2</div>
        <p class="item">我是第1个p标签</p>
        <p class="item">我是第2个p标签</p>  <!-- 希望这个变红 -->
    </section>
</template>
<style>
.item:nth-child(2) { color: red; }
.item:nth-of-type(1) { color: red; }
</style>

我们发现第一个、第二个、第三个都标红了,.item:nth-child(2)还是第二个标红,.item:nth-of-type(1)让第一个和第三个标红,解释跟上面一样同类型的第一个子元素

相关文章

  • 深入理解nth-child和nth-of-type

    定义 :nth-child(n)选择器匹配父元素中的第n个子元素,元素类型没有限制,n可以是数字或公式:nth-o...

  • nth-child(n)和:nth-of-type(n)的区别

    css中的:nth-child(n)和:nth-of-type(n)的区别

  • 笔试题整理(十)

    百度 一、辨析nth-child()和nth-of-type() p:nth-child(2)的含义:①该标签是其...

  • nth-child & nth-of-type

    nth-child和nth-of-type区别 上面示例中,nth-child会在B的同级元素节点中寻找符合的元素...

  • css3新特性

    css3: 1、选择器:nth-child()、nth-of-type()、:checked、:disabled ...

  • jquery

    jQuery的API: 1.选择器: > + ~ nth-child(编号),nth-of-type(编号),[...

  • css3结构性伪类

    nth-child和nth-of-type这两个伪类的区别 例如下题: 理解了这两个伪类的区别之后这个题就很简单了...

  • jQuery

    jQuery的API: 1.选择器: > + ~ nth-child(编号),nth-of-type(编号),[属...

  • jquery

    jQuery的API: 1.选择器: > + ~ nth-child(编号),nth-of-type(编号),[属...

  • jquery

    jQuery的API: 1.选择器: > + ~ nth-child(编号),nth-of-type(编号),[属...

网友评论

      本文标题:深入理解nth-child和nth-of-type

      本文链接:https://www.haomeiwen.com/subject/hejtpltx.html