DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> 關於CSS
CSS 分組與嵌套:少寫 class 的兩個關鍵技巧
編輯:關於CSS     

Grouping 分組

當多個選擇器需要同一組宣告時,用逗號把它們串起來即可:

h2 {
    color: red;
}
.thisOtherClass {
    color: red;
}
.yetAnotherClass {
    color: red;
}

可以合併成:

h2, .thisOtherClass, .yetAnotherClass {
    color: red;
}

Nesting 嵌套

如果 CSS 結構規劃得當,你其實不需要滿地的 class 與 ID——因為 CSS 允許你描述「某選擇器内部的某選擇器」。

#top {
    background-color: #ccc;
    padding: 1em;
}
#top h1 {
    color: #ff0;
}
#top p {
    color: red;
    font-weight: bold;
}

它讓 HTML 乾淨多少

對應的結構可以簡潔到這種程度:

<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,那通常就是巢狀沒寫好的訊號,值得回頭清理。

反過來說,巢狀支援多層疊加,威力很強但也容易失控——選擇器越長,優先級越高、越難被覆寫。這是需要靠練習拿捏的分寸。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved