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