一、避免過度約束
一條普遍規(guī)則,不要添加不必要的約束。
代碼如下:
// 糟糕
ul#someid {..}
.menu#otherid{..}
// 好的
#someid {..}
#otherid {..}
二、后代選擇符最爛
不僅性能低下而且代碼很脆弱,html代碼和css代碼嚴(yán)重耦合,html代碼結(jié)構(gòu)發(fā)生變化時(shí),CSS也得修改,這是多么糟糕,特別是在大公司里,寫html和css的往往不是同一個(gè)人。
代碼如下:
// 爛透了
html div tr td {..}
三、避免鏈?zhǔn)剑ń患┻x擇符
這和過度約束的情況類似,更明智的做法是簡單的創(chuàng)建一個(gè)新的CSS類選擇符。
代碼如下:
// 糟糕
.menu.left.icon {..}
// 好的
.menu-left-icon {..}
四、堅(jiān)持KISS原則
想象我們有如下的DOM:
代碼如下:
下面是對應(yīng)的規(guī)則……
代碼如下:
// 糟糕
#navigator li a {..}
// 好的
#navigator {..}
五、使用復(fù)合(緊湊)語法
盡可能使用復(fù)合語法。
代碼如下:
// 糟糕
.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 {..}
七、避免不必要的重復(fù)
盡可能組合重復(fù)的規(guī)則。
代碼如下:
// 糟糕
.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;
}
八、盡可能精簡規(guī)則
在上面規(guī)則的基礎(chǔ)上,你可以進(jìn)一步合并不同類里的重復(fù)的規(guī)則。
代碼如下:
// 糟糕
.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;
}
九、避免不明確的命名約定
最好使用表示語義的名字。一個(gè)好的CSS類名應(yīng)描述它是什么而不是它像什么。
十、避免 !importants
其實(shí)你應(yīng)該也可以使用其他優(yōu)質(zhì)的選擇器。
十一、遵循一個(gè)標(biāo)準(zhǔn)的聲明順序
雖然有一些排列CSS屬性順序常見的方式,下面是我遵循的一種流行方式。
代碼如下:
.someclass {
/* Positioning */
/* Display & Box Model */
/* Background and typography styles */
/* Transitions */
/* Other */
}
十二、組織好的代碼格式
代碼的易讀性和易維護(hù)性成正比。下面是我遵循的格式化方法。
代碼如下:
// 糟糕
.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;
}
顯然,這里只講述了少數(shù)的規(guī)則,是我在我自己的CSS中,本著更高效和更易維護(hù)性而嘗試遵循的規(guī)則。如果你想閱讀更多的知識,我建議閱讀MDN上的編寫高效的CSS和谷歌的優(yōu)化瀏覽器渲染指南。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com