nth-child(n)和nth-of-type(n)的区分

一.nth-of-type(n)和nth-child(n)区别

1.nth-child(n)
意为在父元素下找到第一个元素
第一个元素为span—字体为红色
第一个元素为其他类型元素 —-字体颜色不设置
也就是说想要对应的样式生效,要同时满足type和n(即父元素的第一个子元素是span或者span是父元素的第一个子元素)
2.nth-of-type(1)
意为在父元素下找到第一个type为span的元素(即使这个span元素在父元素中不是第一顺位)

二.nth-of-type(n)和nth-child(n)例子

这里写图片描述

<!DOCTYPE html>
<html>
<head>
<title>nth-of-type(n)和nth-child(n)</title>
<meta charset='utf-8' />
<style> 
    .demo1 li:nth-of-type(1){
        color:red;
    }
    .demo2 li:nth-child(1){
        color:red;
    }
</style>
</head>
    <body>
        <h1>nth-of-type(1)</h1>
        <div class="demo1">

            <li></li>
            <li></li>
            <li></li>
        </div>
        <h1>nth-child(1)</h1>
        <div class="demo2">
            <li></li>
            <li></li>
            <li></li>
        </div>

    </body>
</html>

这里写图片描述

<!DOCTYPE html>
<html>
<head>
<title>nth-of-type(n)和nth-child(n)</title>
<meta charset='utf-8' />
<style> 
    .demo1 span:nth-of-type(1){
        color:red;
    }
    .demo2 span:nth-child(1){
        color:red;
    }
</style>
</head>
    <body>
        <h1>nth-of-type(1)</h1>
        <div class="demo1">

            <li></li>
            <span>特殊</span>
            <li></li>
            <li></li>
        </div>
        <h1>nth-child(1)</h1>
        <div class="demo2">
            <li></li>
            <span>特殊</span>
            <li></li>
            <li></li>
        </div>

    </body>
</html>

三.总结

当父元素下的子元素是同一个类型时,nth-child(n)和nth-of-type(n)的表现一致
当父元素下的子元素是多种类型的时,nth-child(n)和nth-of-type(n)的表现可能会不一致,但使用nth-of-type(n)应该总有元素会受到样式的影响,使用nth-child(n)咋可能不会对元素进行影响

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值