後代選擇器與群組選擇器可以合併使用,讓同一份樣式套用到多個不同位置的子元素上,是精簡 CSS 很實用的一招。下面是一個具體例子:
<style>
.father .child1,.child2{
border:1px solid red;margin:5px;
}
</style>
<div class="father">
沒有邊框
<p class="child1">有邊框</p>
<p class="child2">有邊框</p>
</div>
效果如下:
有邊框
有邊框
這裡藏著一個很容易踩到的細節:逗號會切斷選擇器的語境。.father .child1 的意思确实是「.father 裡面的 .child1」,但 .child2 前面沒有帶後代關係,所以它其實是全域的 .child2。也就是說,即使某個 .child2 完全不在 .father 裡面,樣式一樣會生效。
如果原意是「.father 裡面的 child1 與 child2 都要有邊框」,正確寫法應該是:
.father .child1, .father .child2 { ... }
或用更簡潔的寫法:
.father .child1, .father .child2 → 也可寫成 .father :is(.child1, .child2)
寫群組選擇器時,養成「每個逗號後都補上完整前綴」的習慣,可以省下不少除錯時間。