所謂 CSS 簡寫,就是把多行的屬性宣告濃縮成一行,也稱作 CSS 程式碼優化。它最大的好處是能顯著縮小 CSS 檔案,但這只是其中一項益處。臃腫雜亂的樣式表會讓除錯變得棘手,尤其當整個團隊協作時,凌亂的程式碼還會拖垮其他人的工作效率。
不少人習慣用 Dreamweaver 這類所見即所得的軟體編寫 CSS,結果產出的程式碼往往過於臃腫。別擔心,讀完本文,你就能掌握程式碼優化的訣竅,讓往後的每一份樣式表都整潔又精簡。
如果屬性值為 0,就不必加單位(如 px、em)。你可能會寫:
padding: 10px 5px 0px 0px;
但其實可以簡化成:
padding: 10px 5px 0 0;
選擇器(如 h1、div、strong 等)是你套用樣式的基本方式。但當你已用 class 或 id 時,就不必再把標籤選擇器寫進宣告裡。例如:
div#logowrap
可以精簡為:
#logowrap
這裡多餘的選擇器就是 div。
* 是萬用符號,可為部分或全部元素套用樣式,但要避免讓它「亂開玩笑」。例如:
* {
margin: 0;
}
這會把所有元素的 margin 設為 0。若想更嚴謹、把範圍限定在某區域,可以這樣寫:
#menu * {
margin: 0;
}
這只會把 #menu 底下所有元素的 margin 設為 0。
你可能會把背景寫成三行:
background-image: url("logo.png");
background-position: top center;
background-repeat: no-repeat;
其實可以合併為:
background: url(logo.png) no-repeat top center;
顏色通常以「#加六位數」的十六進位表示。若顏色由三對成對出現的數字組成,就能省略每對中的一個:
#000000 可寫成 #000,#336699 可寫成 #369。
但這招只適用於成對出現的顏色,像 #010101、#223345、#FFF000 就不適用。
你可能會逐邊宣告:
margin-top: 0px;
margin-right: 10px;
margin-bottom: 0px;
margin-left: 10px;
把值為 0 的單位去掉、再合併成一條:
margin: 0 10px 0 10px;
宣告 margin、padding、border 等屬性時,記得按順時針方向(上、右、下、左)排列。若上下值相等、左右值相等,還能進一步精簡,省略後兩個值,此時前者代表上下、後者代表左右:
margin: 0 10px;
也就是左右為 10px、上下為 0。
padding 的簡寫邏輯與 margin 相同。逐邊宣告:
padding-top: 0px;
padding-right: 10px;
padding-bottom: 0px;
padding-left: 10px;
可以寫成:
padding: 0 10px;
邊框的簡寫最容易記混順序。若要一個 1px 的黑色實線邊框,你可能寫成:
border-width: 1px;
border-style: solid;
border-color: #000;
其實可以寫成:
border: 1px solid #000;
注意這裡的顏色值已用了前述的顏色簡寫法。此外,還能為四邊設定不同寬度:
border-top-width: 1px;
border-right-width: 2px;
border-bottom-width: 3px;
border-left-width: 4px;
可簡寫成:
border-width: 1px 2px 3px 4px;
若只想設定特定幾邊,例如右下邊框:
border: 1px solid #000;
border-width: 0 1px 1px 0;
也就是先設定四邊的預設風格,再宣告哪一邊要顯示。
你可能會把文字樣式寫成一大串:
font-style: italic;
font-variant: small-caps;
font-weight: bold;
font-size: 1em;
line-height: 150%;
font-family: 宋體, Arial, sans-serif;
其實能濃縮成一行:
font: italic small-caps bold 1em/150% 宋體, Arial, sans-serif;
你可能會逐項宣告:
list-style-type: square;
list-style-position: inside;
list-style-image: url(filename.gif);
可以寫成:
list-style: square inside url(filename.gif);
希望這 10 個 CSS 縮寫技巧,能讓你的樣式表寫得更精煉、更好維護。