善用縮寫能顯著縮小 CSS 檔案,可讀性也更好。以下把常用的幾類整理成對照表。
十六進位色碼若每兩位相同,可以縮成一半:
#000000 → #000 #336699 → #369
四種寫法,順序一律是「上、右、下、左」,順時鐘方向:
property: value1; /* 四邊相同 */ property: value1 value2; /* 上下 = 1,左右 = 2 */ property: value1 value2 value3; /* 上 = 1,左右 = 2,下 = 3 */ property: value1 value2 value3 value4; /* 依序為上、右、下、左 */
實例:margin: 1em 0 2em 0.5em;
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-family,寫成 font: 700 14px/22px;,在 Firefox 下會完全不生效。完整寫法是 font: 700 14px/22px arial;。
.login_top {
height: 26px;
font: bold 14px/26px "宋體";
border: 1px solid #000;
}
.login_top2 {
height: 26px; line-height: 26px;
font-weight: bold; font-size: 14px;
border: 1px solid #000; font-family: '宋體';
}
換句話說,縮寫字體時 font-size 與 font-family 兩者至少要有一個明確定義,否則整條宣告會被瀏覽器丟棄。
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 與 border 很像,差別在於 border 會佔用盒模型的空間,outline 不會(因此不會推擠版面)。
outline-width: 數字 + 單位; outline-style: none | dashed | dotted | double | groove | inset | outset | ridge | solid; outline-color: 顏色;
屬性值為 0 時不必加單位,margin:0 就對了,寫 0px 只是多打幾個字。
padding: 4px 6px 3px 4px; → 上4 右6 下3 左4 padding: 1px 2px 3px; → 上1 右2 下3 左2(省略的左 = 右) padding: 5px 10px; → 上下5 左右10(省略的下 = 上) padding: 3px; → 四邊皆 3px
border-width、border-color、margin 等所有涉及四邊的屬性,規則完全一致。
margin-top: 0px; margin-right: 10px; margin-bottom: 0px; margin-left: 10px; margin: 0 10px 0 10px; /* 第一步:去掉 0 的單位並合併 */ margin: 0 10px; /* 第二步:上下相同,再省一組 */
如果已經用了 class 或 id,就不必再把標籤寫進去:
div#logowrap → #logowrap
* 是萬用選擇器,可以一次對一批元素下宣告:
* { margin: 0; }
但全域歸零這種事,寫成全域有時反而危險。限定範圍會嚴謹得多:
#menu * { margin: 0; } /* 只清 #menu 底下所有元素的 margin */