Css Combinators 有以下四種
- descendant selector (space)
- child selector (>)
- adjacent sibling selector (+)
- general sibling selector (~)
以這個html為例,html都是巢狀,所以是一層包一層的結果,如果我們想要選擇下層的標籤內容,可以使用descendant selector 語法是:在上層跟下層中間加上一個”空白”
<!DOCTYPE html>
<html>
<head>
<style>
div p {
background-color: yellow;
}
</style>
</head>
<body>
<h2>Descendant Selector</h2>
<p>The descendant selector matches all elements that are descendants of a specified element.</p>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<section><p>Paragraph 3 in the div.</p></section>
</div>
<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>
</body>
</html>
output
將style更換成child selector如下
<style>
div > p {
background-color: yellow;
}
</style>
可以發現畫面paragraph3沒有變成黃色
再將style更改如下
div + p {
background-color: yellow;
}
</div>
<p>Paragraph 4. Not in a div.</p>
所以只有paragraph4被選中
最後是general sibling selector,只要相同層級並且順序在自己後面,就可以使用
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<section><p>Paragraph 3 in the div.</p></section>
</div>
<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>
如圖,paragraph4跟paragraph5都跟div同個層級,又在div後面,所以會被選中