CSS3---3.相對父元素的偽類


a)之前學習的:a:hover  a:link  a:active  a:visited
b)以某元素相對於其父元素或兄弟元素的位置來獲取無素的結構偽類
f)E:first-child:查找E這個元素的父元素的第一個子元素E
g)E:last-child:最后一個子元素
h)E:nth-child(n): 第n個子元素,計算方法是E元素的全部兄弟元素
i)E:nth-last-child(n): 同E:nth-child(n) 相似,只是倒着計算
j)E:nth-child(even): 所有的偶數
k)E:nth-child(odd): 所有的奇數
l)E:nth-of-type(n):指定類型
m)E:empty 選中沒有任何子節點的E元素,注意,空格也算子元素
n)E:target 結合錨點進行使用,處於當前錨點的元素會被選中
o)重點說明:n遵循線性變化,其取值0、1、2、3、4、... 但是當n<=0時,選取無效
p)案例代碼:
/*第一個li元素*/
li:first-child{
    color: red;
}
/*最后一個元素*/
li:last-child{
    color: green;
}
/*獲取第10個元素*/
li:nth-child(10){
    color: orange;
}
/*獲取倒數第3個li元素*/
li:nth-last-child(3){
    color: purple;
}
/*獲取索引順序為6的倍數的li元素*/
li:nth-child(6n){
    text-decoration: underline;
    border: 1px solid red;
}
/*獲取所有索引為偶數的li元素*/
li:nth-child(even){
    border: 1px solid black;
}
/*獲取前5個li元素*/
li:nth-child(-n+5){
    background-color: #ddd;
}
c)n可是多種形式:nth-child(2n)、nth-child(2n+1)、nth-child(-n+5)等
        li:first-child{
            background-color: lightgray;
        }
        li:last-child{
            background-color: skyblue;
        }


如果在第一個li前面加上div標簽,則第一個不會有灰色底色,只認元素,不認li

        li:first-of-type{
            color: green;
        }
        li:last-of-type{
            color: orange;
        }

改變第一個和最后一個li的字體顏色,之篩選li的父元素ul下的li元素

        /*指定索引位置 nth-child(從1開始的索引||關鍵字||表達式)*/
        li:nth-child(5){
            font-weight: 900;
        }

        /*偶數個元素添加背景  even:偶數  odd:奇數*/
        li:nth-child(even){
            background-color: lightcyan;
        }
        li:nth-child(odd){
            background-color: pink;
        }


同樣需要注意的是這樣的篩選依然是元素的篩選,並不是li標簽的篩選
當我在li前添加div標簽元素的時候,因為div不顯示,所以導致奇數偶數塊交換

同時第4個li的加粗也表明了div的存在

//這樣才是只篩選li元素的奇偶
li:nth-of-type(even){
            background-color: lightcyan;
        }
        li:nth-of-type(odd){
            background-color: pink;
        }

        /*想為前面的5個元素添加樣式*/
        /*n:默認取值范圍為0~子元素的長度.但是當n<=0時,選取無效
        0>>5
        1>>4
        ...
        4>>1
        5>>0*/
        li:nth-last-of-type(-n+5){
            font-size: 30px;
        }
        li:nth-of-type(-n+3){
            font-size: 30px;
        }


免責聲明!

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



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