當多個選擇器需要同一組宣告時,用逗號把它們串起來即可:
h2 {
color: red;
}
.thisOtherClass {
color: red;
}
.yetAnotherClass {
color: red;
}
可以合併成:
h2, .thisOtherClass, .yetAnotherClass {
color: red;
}
如果 CSS 結構規劃得當,你其實不需要滿地的 class 與 ID——因為 CSS 允許你描述「某選擇器内部的某選擇器」。
#top {
background-color: #ccc;
padding: 1em;
}
#top h1 {
color: #ff0;
}
#top p {
color: red;
font-weight: bold;
}
對應的結構可以簡潔到這種程度:
<div id="top">
<h1>Chocolate curry</h1>
<p>This is my recipe for making curry purely with chocolate</p>
<p>Mmm mm mmmmm</p>
</div>
關鍵在於「用空格分隔選擇器」:瀏覽器會理解成「#top 裡面的 h1」與「#top 裡面的 p」,於是標題變黃、段落變紅加粗,全程不必替每個標籤掛 class。
如果你在 HTML 裡看到一堆為了對應樣式而存在的 class 或 id,那通常就是巢狀沒寫好的訊號,值得回頭清理。
反過來說,巢狀支援多層疊加,威力很強但也容易失控——選擇器越長,優先級越高、越難被覆寫。這是需要靠練習拿捏的分寸。