今天就来一起看一下css选择器中的子代选择器中的nth,nth的使用有一定的限制:选中的元素必须是某个父元素下的第n个子元素,今天以表格为例,看一看nth选择器的效果
初始效果:
1.:first-child() 父元素中的第一个子元素
//table中的tr元素中的第一个
tr:first-child{
background-color: skyblue;
font-size: 28px;
font-weight: 700;
}
效果图:
2.:last-child()父元素中的最后一个子元素
//table里的子元素tr的最后一个
tr:last-child{
background-color: skyblue;
font-size: 28px;
font-weight: 700;
}
效果图:
3.:nth-child(n)父元素中的第n个子元素
//子元素的第三个
tr:nth-child(3){
background-color: skyblue;
font-size: 28px;
font-weight: 700;
}
效果图
4.:nth-child(-n+2)多选之前几个
//前几个就是-n+几
tr:nth-child(-n+2){
background-color: skyblue;
font-size: 28px;
font-weight: 700;
}
5.:nth-child(odd/2n+1/2n-1)多选之奇数
tr:nth-child(2n+1){
background-color: skyblue;
font-size: 28px;
font-weight: 700;
}
tr:nth-child(2n-1){
background-color: skyblue;
font-size: 28px;
font-weight: 700;
}
tr:nth-child(odd){
background-color: skyblue;
font-size: 28px;
font-weight: 700;
}
6.:nth-child(even/2n)多选之偶数
tr:nth-child(2n){
background-color: skyblue;
font-size: 28px;
font-weight: 700;
}
tr:nth-child(even){
background-color: skyblue;
font-size: 28px;
font-weight: 700;
}
效果图:
7.:nth-child(n+3)多选之后几个
//n+几,就是后几个
tr:nth-child(n+3){
background-color: skyblue;
font-size: 28px;
font-weight: 700;
}
效果图: