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;
            }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM