CSS3 伪类选择器 nth-child

有时候我们在处理多个同样的<span><.li>等时,其中有一两个需要与其他兄弟不一样,这时候我们就需要css3的伪类选择器 nth-child。下面总结一下几种选取方式

以下HTML css 共用

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <style>
            ul{
                width: 200px;
                height: 20px;
                display: flex;
            }
            ul li{
                list-style: none;
                background-color: gold;
            }
    
        </style>
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
            <li>7</li>
        </ul>
    </body>
</html>

效果图:

1. e:first-child

选取第一个元素,在css添加

li:first-child{
                background-color: blue;
            }

 2.e.last-child

选取最后一个元素

li:last-child{
                background-color: pink;
            }

 3.e.nth-child(number)

选取里面第几个的元素

li:nth-child(4){
                background-color: plum;
            }

 4 e.nth-child(2n);

选取里面偶数元素

li:nth-child(2n){
                background-color: green;
            }

 5.e:nth-child(2n-1)

选取里面奇数的元素

li:nth-child(2n-1){
                background-color: #FFFFFF;
            }

 6.e:nth-child(n+3)

选取从里面第三个开始到最后一个

li:nth-child(n+3){
                background-color: blanchedalmond;
            }

 7.e:nth-child(-n+3)

选取从0到第三个的所有元素

li:nth-child(-n+3){
                background-color: indianred;
            }

  8.e:nth-last-child(3)

选取倒数第三个元素

li:nth-last-child(3){
                background-color: gray;
            }

 9.e:nth-last-child(n+3)

选取从倒数第三到第一个之间的元素

li:nth-last-child(n+3){
                background-color: gray;
            }

原文地址:https://www.cnblogs.com/smile-xin/p/11512495.html