所謂 CSS 簡寫,就是在效果完全相同的前提下,把多行宣告壓縮成一行。它讓程式碼更短,也逼你記住屬性之間的順序關係。以下逐一拆解最常遇到的幾個。
font: italic small-caps bold 12px/1.5em arial, verdana;
/* 等同於 */
font-style: italic;
font-variant: small-caps;
font-weight: bold;
font-size: 12px;
line-height: 1.5em;
font-family: arial, verdana;
順序為 style → variant → weight → size/line-height → family。關鍵細節:font-size 與 line-height 必須用斜線相連,兩者不能分開寫;而 font-family 一定要放在最後。
background: #fff url(bg.gif) no-repeat fixed left top;
/* 等同於 */
background-color: #fff;
background-image: url(bg.gif);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: left top;
順序為 color → image → repeat → attachment → position。實務上常見的簡化寫法是 background: #fff url(bg.gif) no-repeat;,其餘交給預設值。
margin: 1px 0 2em -20px;
/* 等同於 */
margin-top: 1px;
margin-right: 0;
margin-bottom: 2em;
margin-left: -20px;
順序為上、右、下、左。padding 的規則與 margin 一模一樣。
border: 1px solid #000;
/* 等同於 */
border-width: 1px;
border-style: solid;
border-color: #000;
順序為 width → style → color。這三個值組成了「四邊合一」的寫法,也就是同一組結構再套上一層四邊規則。
border-top: 1px solid #000;
/* 等同於 */
border-top-width: 1px;
border-top-style: solid;
border-top-color: #000;
border-right、border-bottom、border-left 依此類推。實務上最常用的是只畫一條分隔線:border-bottom: 1px solid #eee;。
簡寫會把未指定的子屬性重設為初始值。所以如果你先前設定了 border-left-color: red,之後又寫 border: 1px solid #000,左邊框的紅色就會被覆蓋掉。這是多數「簡寫後樣式莫名跑掉」問題的根源。