nth-child选择器,选择指定的li

有了nth-child选择器,选择指定的li时候,就不用写额外的类名,如下:

        ul li {
            width: 20px;
            height: 20px;
            background-color: red;
            margin-bottom: 10px;
            list-style: none;
        }
    <ul>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
  1. 我要让除了第一个li的其他所有li都变成绿色:

方法一:

        ul li:nth-child(n+2) { 
            background-color: green;
        }
        /* n从0开始,表示从第二个开始 */

方法二:

        ul li:not(:first-child) {  
            background-color: green;
        }
        /* 取反 */

页面上:
在这里插入图片描述
2. 我要让最后两个li都变成绿色:

        ul li:nth-child(n+3) {     
            background-color: green;
        }
         /* n从0开始,表示从第三个开始 */

页面上效果:
在这里插入图片描述
3. 我想让除了最后一个li的其他所有li变成绿色
方法一:

        ul li:nth-last-child(n+2) { 
            background-color: green;
        }
     /* n从0开始,这里有一个nth-last-child,表示从最后一个开始,
        n+2表示从倒数二个开始 */

方法二:

        .sel div:not(:last-child) { 
            background-color: green;
        }

页面效果:
在这里插入图片描述
4.我要所有2二点倍数的li变为绿色:
方法一:

        ul li:nth-child(2n) {     
            background-color: green;
        }
         /* 同理3的倍数时3n, 5的倍数时5n */

方法二:

        ul li:nth-child(even) {     
            background-color: green;
        }

页面效果:
在这里插入图片描述
5.所有偶数行蓝色,所有奇数行黄色

        ul li:nth-child(even) {     
            background-color: #87ceeb;
        }
        ul li:nth-child(odd) {     
            background-color: #ffff00;
        }

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

参考:
https://blog.csdn.net/hcwbr123/article/details/80846862

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值