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

原文地址:https://www.cnblogs.com/Tobenew/p/10521317.html