关于CSS3中 nth-child 与 nt-of-type 的区别

首先,nth-child 是选择父元素里面的第几个子元素,不管是第几个类型,而 nt-of-type 是选择指定类型的元素。

举例说明:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div :nth-child(1) {
            background-color: pink;
        }
        
        div :nth-child(2) {
            background-color: purple;
        }

        /* 这个选不到 因为 nth-child 是选择父元素里面的第几个子元素,不管是第几个类型*/
        div span:nth-child(1) {  
            background-color: pink;
        } 

        /* 此时选取的是div中的第二个子元素,即是对第一个 span 标签操作 */
        div span:nth-child(2) {
            background-color: pink;
        } 

        /* 总结: :nth-child(n)  选择 父元素里面的第 n个孩子, 它不管里面的孩子是否同一种类型 */
        /* of-type 选择指定类型的元素 以下三行代码是对div中的 span 进行操作*/
        
        div span:first-of-type {
            background-color: purple;
        }
        
        div span:last-of-type {
            background-color: skyblue;
        }
        
        div span:nth-of-type(2) {
            background-color: red;
        }
    </style>
</head>

<body>
    <div>
        <p>我是一个段落</p>
        <span>我是span1</span>
        <span>我是span2</span>
        <span>我是span3</span>
    </div>
    <!-- ul 里面我们只允许放li  所以 nth-child 和 nth-of-type 就一样了 -->
    <ul>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</body>

</html>

注:E:nth-child(n) 与 E:nth-of-type(n) 中的n是从0开始的,且第 0 个元素或者超出了元素的个数会被忽略,如 -n+5 表示前五个元素。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值