CSS3 伪类选择器 nth-child() 的用法

CSS3 伪类选择器 nth-child() 的用法

:nth-child()选择某个元素的一个或多个特定的子元素,从这个元素的第一个子元素开始算
            .main div:nth-child(3){/*参数是整数*/
                background-color: red;/*选择main中的第三个div,将背景颜色改成红色*/
            }
            .main div:nth-child(n+6){/*参数n+x,x是整数*/
                background-color: orange;/*选择main中的>=6的div,将背景颜色改成橙色*/
            }
            .main div:nth-child(-n+2){/*参数-n+x,x是整数*/
                background-color: yellow;/*选择main中的<=2的div,将背景颜色改成黄色*/
            }
            .main div:nth-child(5n){/*参数x*n,x是整数*/
                background-color: green;/*选择main中的5的倍数的div,将背景颜色改成绿色*/
            }
            .main div:nth-child(4n+2){ /*参数x*n+y,x,y是整数*/
                background-color: blue;/*每4个选一个,选第2个,将背景颜色改成蓝色*/
            }
:nth-last-child()选择某个元素的一个或多个特定的子元素,从这个元素的最后一个子元素开始算

:nth-last-child()选择器和前面的:nth-child()很相似,只是这里多了一个last,所以他起的作用就和前面的":nth-child"不一样了,他只要是从最后一个元素开始算,来选择特定元素。

.main div:nth-last-child(2){/*参数是整数*/
    background-color:blue;/*选中倒数第二div,将背景颜色改成蓝色*/
}
:first-child选择某个元素的第一个子元素,:last-child选择某个元素的最后一个子元素
.main div:first-child{
    background-color: black;/*选中第一个div,将背景颜色改成黑色*/
}
.main div:last-child{
    background-color: black;/*选中最后一个div,将背景颜色改成黑色*/
}
:nth-of-type()选择指定的元素

:nth-of-type(n)选择器匹配同类型中的第n个同级兄弟元素。

n可以是一个数字,一个关键字,或者一个公式。

可以将n设置为odd(奇数)或even(偶数)
.main div:nth-of-type(odd){
    background-color:blue;/*选中奇数div,将背景颜色改成蓝色*/
}
.main div:nth-of-type(even){
    background-color:red;/*选中偶数div,将背景颜色改成红色*/
}
也可以将n设置为表达式,比如,nth-of-type(3n+2),与nth-child()相似
.main div:nth-of-type(4n+2){ /*参数x*n+y,x,y是整数*/
    background-color:red;/*每4个选一个,选第2个,将背景颜色改成红色*/
}
:nth-last-of-type()选择指定的元素,从元素的最后一个开始计算,与:nth-last-child()选择器相似
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值