萬盛學電腦網

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

CSS 縮寫技巧大全:顏色、盒模型、邊框、背景、字體、列表一次掌握

為什麼要縮寫?

  • 減少檔案體積(Gzip 前後皆有效)。
  • 提升可讀性:相關屬性聚合,維護時一眼看清完整意圖。
  • 避免重複覆寫:單一聲明取代多行,降低順序錯誤風險。

六大類縮寫規則速查

1. 顏色:十六進制縮寫

/* 每兩位相同時可縮寫為一位 */
#000000 → #000
#336699 → #369
#FFAA00 → #FA0
/* 不成對者不可縮寫:#010101、#223345、#FFF000 */

現代專案建議統一用 6 位數(或 8 位含透明度 #RRGGBBAA),避免團隊混用造成困擾。

2. 盒模型:margin / padding / border-width / border-radius

/* 四值順時針:上 右 下 左 */
margin: 1rem 2rem 1.5rem 0.5rem;

/* 三值:上、左右、下 */
padding: 1rem 2rem 1.5rem;

/* 兩值:上下、左右 */
border-width: 1px 2px;

/* 一值:四邊相同 */
border-radius: 8px;

記憶口訣:「上右下左,順時針轉」。

3. 邊框:border 合併寫法

/* 語法:border: width style color; */
border: 1px solid #000;

/* 單邊單獨設定 */
border-left: 2px dashed red;
border-bottom: 1px solid #ccc;

/* 進階:先設預設,再覆寫單邊 */
border: 1px solid #000;
border-width: 0 1px 1px 0; /* 只顯示右、下邊框 */

順序固定:寬度 → 樣式 → 顏色,不可亂序。

4. 背景:background 合併寫法

/* 語法:background: color image repeat attachment position; */
background: #f00 url(bg.png) no-repeat fixed center top;

/* 省略值自動套用預設:
   color: transparent
   image: none
   repeat: repeat
   attachment: scroll
   position: 0% 0% */

現代常用簡寫:

/* 純色 + 圖片置中不重複 */
background: #fff url(logo.svg) no-repeat center / cover;
/*                  ↑ position / size(CSS3 Backgrounds 標準) */

5. 字體:font 合併寫法(最嚴格順序)

/* 必須順序:style → variant → weight → size/line-height → family */
font: italic small-caps bold 1rem/1.5 "PingFang TC", "Microsoft JhengHei", sans-serif;

/* 最小必要:size + family */
font: 1rem/1.5 sans-serif;

/* 常見錯誤:順序亂、漏 size、漏 family、line-height 寫在 size 前 */

⚠️ font 縮寫會重置所有未指定的字體子屬性為預設值(如 font-variant: normal),謹慎使用於繼承鏈中。

6. 列表:list-style 合併寫法

/* 語法:list-style: type position image; */
list-style: square inside url(bullet.svg);
/* 取消預設圓點 */
list-style: none;

實戰範例:卡片元件完整縮寫

.card {
  /* 盒模型 */
  margin: 0 auto 1.5rem;
  padding: 1.5rem;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: #fff url(card-bg.svg) no-repeat right bottom / 120px auto;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);

  /* 字體 */
  font: 1rem/1.6 "PingFang TC", "Microsoft JhengHei", sans-serif;
  color: #333;

  /* 列表(若卡片內含列表) */
  list-style: none;
}

避坑與最佳實踐

  • 不要過度縮寫:僅需修改單一屬性時(如只改 margin-top),用長屬性更清晰、不易誤覆寫。
  • CSS 變數配合縮寫:--spacing: 1rem; margin: var(--spacing) 0; 兼具可維護與簡潔。
  • 避免 font 縮寫覆寫繼承:元件內部文字樣式建議用長屬性或 font-size/font-family 單獨設定。
  • 背景尺寸寫在 position 後:center / cover 需 CSS3 Backgrounds 支援,IE9+ 可用。

總結

CSS 縮寫是「精簡代碼」與「維護陷阱」的雙面刃。掌握六大類順序規則、善用開發者工具檢查計算值、配合 CSS 變數與模組化架構,才能在團隊協作中真正發揮縮寫優勢,而非製造難以除錯的隱性 Bug。

copyright © 萬盛學電腦網 all rights reserved