萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 縮寫屬性完全指南:色彩、盒模型、邊框、背景、字體、列表

CSS 縮寫優勢

善用縮寫可大幅減少 CSS 檔案體積、提升可讀性與維護效率。本文整理六大類常用縮寫規則。

1. 色彩縮寫

十六進制色碼若每兩位相同,可縮寫為 3 位:

color: #113366;  →  color: #136;

適用於所有接受十六進制色值的屬性:background-color、border-color、text-shadow、box-shadow 等。

2. 盒模型縮寫

適用於 margin、padding,順序為順時針:上 → 右 → 下 → 左。

/* 四值完整寫法 */
margin: 1px 2px 3px 4px;

/* 三值:上 | 左右 | 下 */
margin: 1px 2px 3px;  /* 等同 1px 2px 3px 2px */

/* 兩值:上下 | 左右 */
margin: 1px 2px;      /* 等同 1px 2px 1px 2px */

/* 一值:四邊相同 */
margin: 1px;          /* 等同 1px 1px 1px 1px */

注意:margin: 1px 2px 1px 3px 雖上下同為 1px,但左右不同,無法進一步縮寫。

3. 邊框縮寫

border 包含三個子屬性:border-width、border-style、border-color。

border: 5px solid #369;  /* 寬度 樣式 顏色 */

可省略值與預設值

寫法結果說明
border: groove red;3px groove red預設寬度 3px
border: solid;3px solid currentColor預設色為 color 屬性值
border: 5px;無效缺少 style,必須項
border: 5px red;無效缺少 style
border: red;無效缺少 style

結論:border-style 為必填,預設寬度 3px、預設色為元素 color 值(預設黑色)。

單邊與單屬性縮寫

/* 四邊分別設定 */
border-top: 4px solid #333;
border-right: 3px solid #666;
border-bottom: 3px solid #666;
border-left: 4px solid #333;

/* 單屬性多值(同盒模型順序) */
border-width: 1px 2px 3px 4px;
border-style: solid dashed dotted groove;
border-color: red blue white black;

4. Outline 縮寫

outline 類似 border 但不影響盒模型佈局:

outline: 1px solid red;  /* style 為必填 */

預設值同 border。

5. 背景縮寫

background 是最高頻縮寫之一:

background: #fff url(img.png) no-repeat 0 0;
/* 色彩 圖片 重複 定位 */

完整屬性順序:

background: color image repeat attachment position;
/* 預設值 */
background: transparent none repeat scroll 0% 0%;

可省略任意值,瀏覽器將套用預設值。背景屬性不會繼承。

6. 字體縮寫

font 縮寫最複雜也最常用,至少必須包含 font-size 與 font-family:

font: italic small-caps bold 1em/140% "Lucida Grande", sans-serif;
/* style variant weight size/line-height family */

各屬性預設值:

  • font-style: normal
  • font-variant: normal
  • font-weight: normal
  • font-size: inherit
  • line-height: normal
  • font-family: inherit

警示:font 縮寫易因遺漏值導致非預期重置,部分團隊規範建議分開撰寫。

7. 列表樣式縮寫

list-style: none;  /* 清除預設符號,最常用 */

完整三屬性:

list-style-type: square;      /* 符號類型 */
list-style-position: inside;  /* 符號位置 */
list-style-image: url(img.gif); /* 自訂圖片 */

/* 縮寫 */
list-style: square inside url(img.gif);

預設值:list-style: disc outside none。

優先權:若同時設定 list-style-image 與 list-style-type,圖片存在時優先顯示圖片。

8. Border-radius 圓角縮寫(CSS3)

早期需大量瀏覽器前綴:

-moz-border-radius: 0 6px 6px;
-webkit-border-radius: 0 6px 6px;
border-radius: 0 6px 6px;  /* 標準寫法,現代瀏覽器僅需此行 */

順序:左上、右上、右下、左下(順時針),可用 1–4 個值。強烈建議使用縮寫,避免維護惡夢。

CSS Sprites 圖片合併技術補充

將多張小圖合併為一張大圖,透過 background-position 定位,減少 HTTP 請求、提升載入效能。關鍵要點:

  • 按由上至下、由左至右排列,座標易維護
  • 同色系圖片合併可減少色數、壓縮體積
  • 預留足夠間距防止高解析度斷裂
  • 避免使用 bottom/right 定位,以免擴充圖片時座標失效
  • 文字前 icon 放在 Sprite 最左/右邊,最靈活

圖片優化建議

  • 靜態圖優先用 PNG-8 替代 GIF,節省 10–30% 體積
  • Fireworks 輸出 PNG 體積通常優於 Photoshop
  • 使用無損壓縮工具(如 ImageOptim、TinyPNG)進一步優化
  • 單圖建議 ≤100KB、寬度 ≤800px
copyright © 萬盛學電腦網 all rights reserved