关系选择器,nth-child和nth-of-type

关系选择器

  • 后代选择器:E F 选择E元素的所有后代F元素
  • 子选择器:E > F 选择E元素的所有子元素F
  • 相邻同胞选择器:E + F 选择紧接在E元素之后的第一个兄弟元素F
  • 同胞选择器:E ~ F 选择E元素之后的所有兄弟元素F

nth-child和nth-of-type

区别:

nth-of-type为什么要叫:nth-of-type?因为它是以"type"来区分的。也就是说:ele:nth-of-type(n)是指父元素下第n个ele元素。(标签优先)

而ele:nth-child(n)是指父元素下第n个元素且这个元素为ele,若不是,则选择失败。 (顺序优先)

解释及注意:

标签优先

如果是class那么碰到不同类型标签的,单独分类,符合条件的选中。
代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">
    .a:nth-of-type(3){
        color: red;
    }
    </style>
</head>
<body>
    <p class="a">1</p>
    <h1 class="a">2</h1>
    <h1 class="a">3</h1>
    <h1 class="a">4</h1>
    <p class="a">5</p>
    <p class="a">6</p>
</body>
</html>

效果:
在这里插入图片描述

顺序优先

代码1:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style type="text/css">
  .box{
    width: 400px;
    height: 400px;
    background-color: aqua;
  }
  :nth-child(1){
    width: 50px;
    height: 50px;
    background-color: black;
  }
  </style>
</head>
<body>
  <div class="box">
    <div id="a"></div>
    <div id="b"></div>
    <div id="c"></div>
  </div>
</body>
</html>

效果:
在这里插入图片描述
图中一片黑,是因为:nth-child()前面没有加限定,name选择html中第一个元素即html
在这里插入图片描述
代码二:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style type="text/css">
  .box{
    width: 400px;
    height: 400px;
    background-color: aqua;
  }
  div:nth-child(1){
    width: 50px;
    height: 50px;
    background-color: black;
  }
  </style>
</head>
<body>
  <div class="box">
    <div id="a"></div>
    <div id="b"></div>
    <div id="c"></div>
  </div>
</body>
</html>

效果:
在这里插入图片描述
我们发现蓝块块没有了!我个人认为是div这只指定不够明确。
那么我们换为

#a:nth-child(1)

效果:
在这里插入图片描述
ok有效。所以我们使用nth-child()时,限定词应该尽可能准确
另外当限定词为标签但代码中又匹配不对,比如p:nth-child(3)但代码中第三个标签不是p。这是会发生匹配失败,然后无效


参考文章:
深入理解css3中 nth-child 和 nth-of-type 的区别
CSS3选择器:nth-child和:nth-of-type之间的差异
浅谈nth-child和nth-of-type的区别
彻底理解nth-child和nth-of-type的区别。
关系选择器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值