nth-child的使用方法
时间:2023-3-7 17:03 作者:小诸葛 分类: 前端 正在检查是否收录...
废话不说多少先上效果图
图一:
图二:
仔细观察就会发现图二第二行都没有了下边框,虽然解决办法有很多,比如给每个元素单独添加id选择器和类名选择器去逐一选择,但是这样会很麻烦,代码一多也容易造成代码冗余,这里推荐一种方法可以很快捷的实现上面功能。
.nav-fl li:nth-child(n+4){
border-bottom: 0;
}
选择了第四个元素和之后的元素。
更多使用方法如下:
first-child:选择第一个li标签设置字体大小为12px。
li:first-child{
font-size:12px;
}
last-child:选择最后一个li标签设置字体大小为12px。
li:last-child{
font-size:12px;
}
nth-child(n):选择第n个li标签设置字体大小为12px.
li:nth-child(3){
font-size:12px;
}
nth-child(odd):选择为奇数li标签设置字体大小为12px,或者通过nth-child(n+1),nth-child(2n-1) 也可以选择奇数行
li:nth-child(odd){
font-size:12px;
}
nth-child(even):选择的偶数行li设置字体大小为12px,或者通过另外的方法选择奇数行:nth-child(2n)
li:nth-child(even){
font-size:12px;
}
不只是上面的固定写法,还有更灵活的组合方法,例如:
/* 选择前三个元素设置其背景颜色 */
li:nth-child(-n+3){
background: #5555ff;
}
/* 选择第二个元素以及之后的元素 */
li:nth-child(n+2){
background: #0ab1fc;
}
/* 选择第倒数第3个元素 */
li:nth-last-child(3){
background-color: #55007f;
}
/* 选择倒数第三个以及之前的元素*/
li:nth-last-child(n+3) {
background-color: saddlebrown;
}
/* 选择第一个元素和之后每+1个元素状态,1,3,5...*/
li:nth-child(2n+1){
background: red;
}
方法还有很多,可以看以上案例,通过举一反三去实现自己需要的效果,重要的是思想,看到一个效果不要着急上手,先思考如何去实现,以及实现的细节,其次才是上手。
推荐阅读:
扫描二维码,在手机上阅读