编写好的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”