Css nth-child 選擇器

nth-child(even) 雙數

css

1
2
3
4
5
6
7
ul li{
padding:5px;
}
ul li:nth-child(even){
background-color:green;
color:white;
}

Scss

1
2
3
4
5
6
7
8
9
ul {
li{
padding:5px;
&:nth-child(even){
background-color:#ffd207;
color:white;
}
}
}

nth-child(odd) 單數

css

1
2
3
4
5
6
7
ul li{
padding:5px;
}
ul li:nth-child(odd){
background-color:green;
color:white;
}

Scss

1
2
3
4
5
6
7
8
9
ul {
li{
padding:5px;
&:nth-child(odd){
background-color:#ffd207;
color:white;
}
}
}

nth-child(3n) 倍數n

3n 指的是 3 乘 n,而 n 是個由0開始的固定數列 ( 就是 0123456789…n),我們就可以得到下列結果清單

1
2
3
4
5
6
7
8
9
 ul {
li{
padding:5px;
&:nth-child(3n){
background-color:#ffd207;
color:#333;
}
}
}

nth-child(an+b) 倍數an+b

3n+1

  • 3 x 0 + 1 = 1
  • 3 x 1 + 1 = 4
  • 3 x 2 + 1 = 7
  • 3 x 3 + 1 = 10
  • 3 x 4 + 1 = 13
1
2
3
4
5
6
7
8
9
 ul {
li{
padding:5px;
&:nth-child(3n+1){
background-color:#ffd207;
color:#333;
}
}
}

nth-child(an-b) 倍數an-b

3n-1

  • 3 x 0 - 1 = -1
  • 3 x 1 - 1 = 2
  • 3 x 2 - 1 = 5
  • 3 x 3 - 1 = 8
  • 3 x 4 - 1 = 11
1
2
3
4
5
6
7
8
9
 ul {
li{
padding:5px;
&:nth-child(3n-1){
background-color:#ffd207;
color:#333;
}
}
}