寫得好的 CSS 能實際提升頁面渲染速度。原理很直白:瀏覽器需要解析的規則越少,樣式計算就越快。MDN 把選擇器分成四大類,效率由高到低依序是:
*)關於效率的系統性討論,最早可回溯到 Steve Souders 在 2009 年出版的《高性能網站建設進階指南》,Google 的《高效 CSS 選擇器的最佳實踐》也有更細節的說明。以下整理 12 個實用原則。
不要加上不必要的標籤或 class 限定。
/* 糟糕 */ ul#someid {..} .menu#otherid {..}
/* 好的 */ #someid {..} #otherid {..}
除了效能差,它還很脆弱:HTML 與 CSS 高度耦合,結構一動樣式就得跟著改。在大團隊裡寫 HTML 和 CSS 的往往不是同一個人,這個問題會被放大。
/* 爛透了 */ html div tr td {..}
情況和過度約束類似,更明智的做法是開一個語意清楚的新 class。
/* 糟糕 */ .menu.left.icon {..}
/* 好的 */ .menu-left-icon {..}
假設有這樣的 DOM:
<ul id="navigator"> <li><a href="#" class="twitter">Twitter</a></li> <li><a href="#" class="facebook">Facebook</a></li> <li><a href="#" class="dribble">Dribbble</a></li> </ul>
/* 糟糕 */ #navigator li a {..}
/* 好的 */ #navigator {..}
/* 糟糕 */
.someclass {
padding-top: 20px; padding-bottom: 20px;
padding-left: 10px; padding-right: 10px;
background: #000;
background-image: url(../imgs/carrot.png);
background-position: bottom;
background-repeat: repeat-x;
}
/* 好的 */
.someclass {
padding: 20px 10px;
background: #000 url(../imgs/carrot.png) repeat-x bottom;
}
/* 糟糕 */ .someclass table tr.otherclass td.somerule {..}
/* 好的 */ .someclass .otherclass td.somerule {..}
/* 糟糕 */
.someclass { color: red; background: blue; font-size: 15px; }
.otherclass { color: red; background: blue; font-size: 15px; }
/* 好的 */
.someclass, .otherclass { color: red; background: blue; font-size: 15px; }
在上一步的基礎上,把不同 class 間重複的宣告抽調出來,只留下有差異的部分。
/* 好的 */
.someclass, .otherclass {
color: red; background: blue; height: 150px; width: 150px;
}
.someclass { font-size: 16px; }
.otherclass { font-size: 8px; }
好的 class 名應該描述「它是什麼」,而不是「它長什麼樣」。.red-text 在換色當天就會變成一個笑話,.alert-text 才能活得長久。
如果非得靠 !important 才能壓過某條規則,通常代表選擇器的優先權設計出了問題。回頭調整結構會更好。
.someclass {
/* Positioning */
/* Display & Box Model */
/* Background and typography styles */
/* Transitions */
/* Other */
}
可讀性和可維護性成正比。
/* 糟糕 */
.someclass-a, .someclass-b, .someclass-c, .someclass-d { ... }
/* 好的 */
.someclass-a,
.someclass-b,
.someclass-c,
.someclass-d { ... }
/* 多值屬性的換行對齊 */
.someclass {
background-image:
linear-gradient(#000, #ccc),
linear-gradient(#ccc, #ddd);
box-shadow:
2px 2px 2px #000,
1px 4px 1px 1px #ddd inset;
}
這裡只涵蓋了其中一小部分規則,都是實務上最容易見效的幾條。想深入閱讀,可以參考 MDN 的〈編寫高效的 CSS〉與 Google 的〈優化瀏覽器渲染指南〉。