幾天前,同事因為在排版上碰到關於 nth-child
的問題,就來和我討論了一下。起初也覺得困惑的我,在翻了幾篇文章後恍然大悟,最後和他一起解決了這個問題,也才發現原來我對 nth-child
有非常大的誤解,透過這篇文記錄一下。
我們看看 MDN 對於 nth-child
的解釋:
The :nth-child() CSS pseudo-class matches elements based on their position in a group of siblings.
大意是說:nth-child
會依據元素在同輩中的位置去匹配。
也很快看個例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
div,
section {
width: 50px;
height: 50px;
margin: 0.5rem 0;
border: 1px solid black;
}
div:nth-child(1) {
background-color: red;
}
div:nth-child(2) {
background-color: blue;
}
div:nth-child(3) {
background-color: green;
}
div:nth-child(4) {
background-color: yellow;
}
</style>
</head>
<body>
<main>
<div></div>
<div></div>
<div></div>
<div></div>
</main>
</body>
</html>
因為我在上方 div:nth-child(1)~div:nth-child(4) 分別給了 red
, blue
, green
, yellow
的背景色,因此渲染時依序套上了紅、藍、綠、黃四種顏色,看起來非常正常,那如果我們在中間穿插了 section
:
<main>
<div></div>
<section></section>
<div></div>
<section></section>
<div></div>
<section></section>
<div></div>
<section></section>
</main>
明明仍有四個 div
,卻只剩第一個和第二個 div
有顏色,且第二個 div
變成了綠色。
我們很快地在看一次這句話的大意:
nth-child
會依據元素在同輩中的位置去匹配。
接著我們看一下 w3school 對其的解釋:
:nth-child(n) 选择器匹配属于其父元素的第 N 个子元素,不论元素的类型。
看到這裡我就恍然大悟了!以此例子,對 nth-child(n)
來說,n
實際上是從 main
這一層往下找。它看到 div
且是他的第一個子代,因此依照 div:nth-child(1)
內的樣式給予其 red
背景色;接著發現第二個子代是 section
,因此跳過;接著發現第三個子代是 div
,因此依照 div:nth-child(3)
內的樣式給予其 green 背景色,依此類推。
因此,上述例子若要讓 div 皆有對應背景色,正確做法應該是:
div:nth-child(1) {
background-color: red;
}
div:nth-child(3) {
background-color: blue;
}
div:nth-child(5) {
background-color: green;
}
div:nth-child(7) {
background-color: yellow;
}
關於 nth-child
就記錄到這,因為過往在使用它時都是在同層皆為相同元素的情況,幾天前討論後才發現原來自己對它有非常深的誤解。希望這篇文會幫助到碰到相同問題的人,若內容有任何錯誤,也煩請不吝指出,謝謝!
references: