一般原則是:不要加上不必要的約束。
/* 糟糕 */
ul#someid { ... }
.menu#otherid { ... }
/* 好的 */
#someid { ... }
#otherid { ... }
後代選擇符不僅效能低落,程式碼也很脆弱:HTML 結構一改,CSS 就得跟著動。在大團隊裡,寫 HTML 和寫 CSS 的往往不是同一個人,這種耦合會變成協作夢魘。
/* 爛透了 */
html div tr td { ... }
/* 糟糕 */
.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 {
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-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;
}
這些規則看似瑣碎,但在一個數千行的樣式表中,它們決定了三個月後你(或你的同事)是否還看得懂自己在寫什麼。