nth-child()用法
-
nth-child(number)
表示第几个子元素
.div:nth-child(2) /*表示第二个子元素*/
.div:nth-child(4) /*表示第四个子元素*/ -
nth-child(odd)和nth-child(even)
nth-child(odd)表示取出奇数的子元素,即取出第1,3,5,...个子元素
nth-child(even)表示取出偶数的子元素,即取出第2,4,6,...个子元素
-
nth-child(±an+b)
表示从b点,向左或者向右按步长a(a>0)取出子元素,乍一看似乎不明白,举个例子
假如div里面有12个子div,子div的位置[1,2,3,4,5,6,7,8,9,10,11,12]
*{
margin: 0;
padding: 0;
}
body{
display: flex;
justify-content: center;
align-content: center;
}
.father{
width: 500px;
height: 400px;
background-color: red;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-content: center;
}
.child{
width: 100px;
height: 100px;
background-color: yellow;
border: 5px solid white;
z-index: 1;
}
.father .child:nth-child(-1n+2){ /*从第二个子div往左按步长1取出元素*/ =>[1,2]
background-color: blue;
}*{
margin: 0;
padding: 0;
}
body{
display: flex;
justify-content: center;
align-content: center;
}
.father{
width: 500px;
height: 400px;
background-color: red;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-content: center;
}
.child{
width: 100px;
height: 100px;
background-color: yellow;
border: 5px solid white;
z-index: 1;
}
.father .child:nth-child(-2n+10){ /*从第二个子div往左按步长2取出元素*/ =>[2,4,6,8,10]
background-color: blue;
}*{
margin: 0;
padding: 0;
}
body{
display: flex;
justify-content: center;
align-content: center;
}
.father{
width: 500px;
height: 400px;
background-color: red;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-content: center;
}
.child{
width: 100px;
height: 100px;
background-color: yellow;
border: 5px solid white;
z-index: 1;
}
.father .child:nth-child(-2n-10){ /*从第-10个子div往左按步长2取出元素*/ =>取不到子元素
background-color: blue;
}*{
margin: 0;
padding: 0;
}
body{
display: flex;
justify-content: center;
align-content: center;
}
.father{
width: 500px;
height: 400px;
background-color: red;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-content: center;
}
.child{
width: 100px;
height: 100px;
background-color: yellow;
border: 5px solid white;
z-index: 1;
}
.father .child:nth-child(2n-10){ /*从第-10个子div往右按步长2取出元素*/ =>[2,4,6,8,10]
background-color: blue;
} -