前端学习笔记(2)nth-child和:nth-of-type的区别

最近学习css3结构伪类选择器:nth-child和:nth-of-type,这两个比较迷,特地记录一下

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title></title>

    <style>
        .box {
            width: 50%;
            margin: auto;
        }
        
        ul,
        li {
            list-style: none;
        }
        
        .box div,
        p {
            border: 1px solid #008000;
            height: 30px;
            line-height: 30px;
            text-indent: 10px;
        }
        
        .box div {
            margin: 10px auto;
        }
    </style>
</head>

<body>
    <div class="box">
        <p>ppp</p>
        <p>ppp</p>
        <div>div</div>
        <div>div</div>
        <article>article</article>
        <div>div</div>
        <div>div</div>
        <div>div</div>
        <ul>
            <li>ul中的li标签</li>
            <li>ul中的li标签</li>
        </ul>
        <p><span>p标签里面的span标签</span>
        <span>p标签里面的span标签</span></p>
        <span>span</span>
    </div>
</body>

</html>

E:nth-child(n):匹配到父元素的第n个子元素

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

效果如下

.box p:nth-child(2)是把.box中第二个子元素并且是p标签的元素选取出来。

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

效果如下


.box :nth-child(2):这个意味着把.box的所有后代中第二个子元素变成红色,故“ul中的li标签”
和“p标签里面的span标签”也变红了。

E:nth-of-type()表示父元素下的第n个类型的子元素

<style>
    ...
    .box div:nth-of-type(2) {
            background-color: blueviolet;
        }
</style>

效果如下:


.box div:nth-of-type(2):意思是.box后代中是div的元素然后找第二个div元素。

<style>
    ...
    .box :nth-of-type(2) {
            background-color: blueviolet;
        }
</style>

效果如下:


.box div:nth-of-type(2)的意思是选中.box后代中相同元素的第二个,所以p标签的第二个,div标签的第二个,li标签的第二个,span标签的第二个均被选中。

E:nth-child 与 E:nth-of-type 的区别

  • E:nth-child(n) 匹配父元素的第n个子元素E,也就是说,nth-child 对父元素里面所有孩子排序选择(序号是固定的) 先找到第n个孩子,然后看看是否和E匹配
  • E:nth-of-type(n) 匹配同类型中的第n个同级兄弟元素E,也就是说,对父元素里面指定子元素进行排序选择。 先去匹配E ,然后再根据E 找第n个孩子
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值