編寫好的CSS代碼能提高頁面的渲染速度。本質上,一條規則都沒有引擎解析的最快。MDN上將CSS選擇符歸拆分紅四個主要類別,以下所示,性能依次下降。css
對效率廣泛認識是從Steve Souders在2009年出版的《高性能網站建設進階指南》開始的,雖然Souders的書中羅列的很是詳細,你能夠在這裏查看完整列表引用。你也能夠在谷歌的高效的CSS選擇器的最佳實踐中查看更多的細節。html
本文我想分享一些我在編寫高性能CSS中用到的簡單的例子和指導方針。受MDN的編寫高效的CSS指南的啓發,並遵循相似的格式。git
做爲通常規則,不添加沒必要要的約束。github
// 糟糕 ul#someid {..} .menu#otherid{..} // 好的 #someid {..} #otherid {..}
不只性能低下並且代碼很脆弱,html代碼和css代碼嚴重耦合,html代碼結構發生變化時,CSS也得修改,這是多麼糟糕,特別是在大公司裏,寫html和css的每每不是同一我的。瀏覽器
// 爛透了 html div tr td {..}
這和過分約束的狀況相似,更明智的作法是簡單的建立一個新的CSS類選擇符。ide
// 糟糕 .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 20px 10px; background: #000 url(../imgs/carrot.png) repeat-x bottom; }
// 糟糕 .someclass table tr.otherclass td.somerule {..} //好的 .someclass .otherclass td.somerule {..}
儘量組合重複的規則。ui
// 糟糕 .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; }
在上面規則的基礎上,你能夠進一步合併不一樣類裏的重複的規則。
// 糟糕 .someclass { color: red; background: blue; height: 150px; width: 150px; font-size: 16px; } .otherclass { color: red; background: blue; height: 150px; width: 150px; font-size: 8px; } // 好的 .someclass, .otherclass { color: red; background: blue; height: 150px; width: 150px; } .someclass { font-size: 16px; } .otherclass { font-size: 8px; }
最好使用表示語義的名字。一個好的CSS類名應描述它是什麼而不是它像什麼。
其實你應該也可使用其餘優質的選擇器。
雖然有一些排列CSS屬性順序常見的方式,下面是我遵循的一種流行方式。
.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; }
顯然,這些只是極少數的規則,是我在我本身的CSS中,本着更高效和更易維護性而嘗試遵循的規則。若是你想閱讀更多的知識,我建議閱讀MDN上的編寫高效的CSS和谷歌指南上的優化瀏覽器渲染。
本文爲譯文,原文爲「Writing Better CSS」