善用縮寫有兩個好處:檔案體積變小,以及宣告意圖更清楚。以下整理最常用到的幾類屬性。
十六進位色碼若每兩位重複,可以砍半:
#000000 → #000
#336699 → #369
提醒:同一段樣式規則裡不要全寫與縮寫混用。在記憶體極度受限的環境下,混用有時會導致瀏覽器渲染異常。
四個值、三個值、兩個值、一個值,順序一律是「上、右、下、左」,順時鐘方向記最簡單:
property: value1; /* 四邊相同 */
property: value1 value2; /* 上下 = value1,左右 = value2 */
property: value1 value2 value3; /* 上、左右、下 */
property: value1 value2 value3 value4; /* 上 右 下 左 */
例如 margin: 1em 0 2em 0.5em; 就是上 1em、右 0、下 2em、左 0.5em。左右相同時寫成兩值即可,例如 margin: 1em 0;。
三條宣告可以合併:
border-width: 1px;
border-style: solid;
border-color: #000;
/* 等價寫法 */
border: 1px solid #000;
語序為 width style color,三項順序其實可調,但養成固定習慣更好維護。
background-color: #f00;
background-image: url(background.gif);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;
/* 等價寫法 */
background: #f00 url(background.gif) no-repeat fixed 0 0;
語序為 color image repeat attachment position。省略的項目會退回瀏覽器預設值:
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-size 與 font-family 在縮寫中不可省略,而 line-height 要緊跟在 font-size 後面並以斜線分隔。
list-style-type: square;
list-style-position: inside;
list-style-image: url(image.gif);
/* 等價寫法 */
list-style: square inside url(image.gif);
/* 移除項目符號 */
list-style: none;
outline: none;
text-decoration: none;
background-position: center top;
border-radius: 4px 4px 0 0; /* 左上 右上 右下 左下 */
縮寫的價值不只是省字元,更在於把「相關的一組設定」收在同一行,讓後接手的人一眼看出這段樣式在做什麼。