CSS 簡寫(shorthand)就是把多行屬性合併成一行,這麼做最大的好處是檔案更小、載入更快,可讀性也更高。以下整理十個最常用、最實在的簡寫規則。
盒子有上下左右四個方向,分開寫要四行:
margin-top:1px; margin-right:2px; margin-bottom:3px; margin-left:4px;
合併成一行,語法是 margin: top right bottom left(上右下左,順時針):
margin:1px 2px 3px 4px;
參數個數不同,含義也不同:
margin:1px; /* 四邊都是 1px */ margin:1px 2px; /* 上下 1px、左右 2px */ margin:1px 2px 3px; /* 上 1px、左右 2px、下 3px */ margin:1px 2px 1px 3px;/* 上下同為 1px,但四邊值不同,無法再縮 */
border-width:1px; border-style:solid; border-color:#000;
可合併為 border: width style color:
border:1px solid #000;
background-color:#f00; background-image:url(background.gif); background-repeat:no-repeat; background-attachment:fixed; background-position:0 0;
合併為 background: color image repeat attachment position:
background:#f00 url(background.gif) no-repeat fixed 0 0;
其中任何一項都可以省略,省略時會使用瀏覽器預設值:color 為 transparent、image 為 none、repeat 為 repeat、attachment 為 scroll、position 為 0% 0%。
font-style:italic; font-variant:small-caps; font-weight:bold; font-size:1em; line-height:140%; font-family:"Lucida Grande",sans-serif;
合併為:
font:italic small-caps bold 1em/140% "Lucida Grande",sans-serif;
注意:使用 font 簡寫時,font-size 與 font-family 這兩個值至少要明確寫出,否則整行會失效。
要拿掉預設的項目符號,寫 list-style: none 即可。完整屬性有三項:
list-style-type:square; list-style-position:inside; list-style-image:url(image.gif);
list-style:square inside url(image.gif);
當 #RRGGBB 中每兩個字元相同時,可以縮寫成三位:
Aqua #00ffff → #0ff Black #000000 → #000 Blue #0000ff → #00f Dark Grey #666666 → #666 Fuchsia #ff00ff → #f0f Light Grey#cccccc → #ccc Lime #00ff00 → #0f0 Orange #ff6600 → #f60 Red #ff0000 → #f00 White #ffffff → #fff Yellow #ffff00 → #ff0
padding:10px 5px 0px 0px; /* 可寫成 ↓ */ padding:10px 5px 0 0;
#nav{
border-top:4px solid #333;
font-style:normal;
font-variant:normal;
font-weight:normal
}
最後一個屬性後面的分號可以拿掉。不過實務上建議一律保留,因為之後新增屬性時不必回頭補分號。
h1{ font-weight:700; } /* 等同 bold */
p { font-weight:400; } /* 等同 normal */
早期的寫法要為每個轉角與每個瀏覽器核心各寫一行:
-moz-border-radius-bottomleft:6px; -moz-border-radius-topleft:6px; -moz-border-radius-topright:6px; -webkit-border-bottom-left-radius:6px; -webkit-border-top-left-radius:6px; -webkit-border-top-right-radius:6px; border-bottom-left-radius:6px; border-top-left-radius:6px; border-top-right-radius:6px;
現在只要一行就足夠,語法是 border-radius: topleft topright bottomright bottomleft:
border-radius:0 6px 6px;
(前綴版本僅在支援舊版瀏覽器時才需要。)這些簡寫規則搭配起來用,樣式表往往能瘦掉三到五成,後續維護也一目了然。