萬盛學電腦網

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

CSS background 綜合屬性詳解:八大子屬性一次掌握

background 是 CSS 中功能最豐富的簡寫屬性之一,能在單一宣告中設定顏色、圖片、定位、尺寸、重複、繪製區域、捲動行為等八大子屬性。本文逐項拆解語法、預設值、實務技巧,助你寫出精簡且可維護的背景樣式。

八大子屬性總覽

子屬性功能預設值常用值範例
background-color背景顏色transparent#fff, rgba(0,0,0,0.5), hsl(200,50%,80%)
background-image背景圖片(可多層,逗號分隔)noneurl(bg.png), linear-gradient(...), none
background-position圖片初始位置0% 0% (left top)center center, right bottom, 50px 100px
background-size圖片尺寸autocover, contain, 100% 100%, 200px auto
background-repeat重複方式repeatno-repeat, repeat-x, repeat-y, space, round
background-origin定位基準區域padding-boxborder-box, padding-box, content-box
background-clip繪製裁切區域border-boxborder-box, padding-box, content-box, text(文字裁切)
background-attachment捲動行為scrollfixed(視差效果), local(隨元素捲動)

簡寫語法順序與規則

標準順序(順序可互換,但 background-size 必須緊跟在 background-position 後並用 / 分隔):

background: 
  [background-color] 
  [background-image] 
  [background-position] / [background-size] 
  [background-repeat] 
  [background-attachment] 
  [background-origin] 
  [background-clip];

實用範例

/* 1. 基礎:純色 + 置中不重複圖片 */
.bg-basic {
  background: #f5f5f5 url(logo.png) no-repeat center center;
}

/* 2. 響應式全螢幕背景 */
.bg-cover {
  background: url(hero.jpg) no-repeat center center / cover;
  background-attachment: fixed; /* 視差滾動 */
}

/* 3. 多層背景:漸變疊加圖案 */
.bg-multi {
  background: 
    linear-gradient(135deg, rgba(0,0,0,0.6), transparent), /* 頂層 */
    url(pattern.png) repeat 0 0,                             /* 中層 */
    #333;                                                    /* 底層色 */
}

/* 4. 文字裁切背景(漸變文字) */
.text-gradient {
  background: linear-gradient(90deg, #f00, #0f0, #00f);
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
}

/* 5. 內容區域繪製背景(不延伸到 border) */
.bg-content-box {
  border: 10px dashed #ccc;
  padding: 20px;
  background: url(bg.png) no-repeat center / cover;
  background-origin: content-box;  /* 定位基準 */
  background-clip: content-box;    /* 裁切範圍 */
}

常見陷阱與最佳實踐

  1. 漏寫背景色:圖片載入失敗或透明時,background-color 是最後防線,習慣寫在最後或最前。
  2. 多重背景層序:先寫的在上層,最後寫的在最底層(與 z-index 相反直覺)。
  3. background-size 與 position 簡寫:必須用 / 分隔,如 center / cover,否則會被解析為 position 的兩個值。
  4. background-clip: text:需配合 color: transparent,且需加 -webkit- 前綴支援 Safari/舊版 Chrome。
  5. 效能:background-attachment: fixed 在移動端可能造成卡頓,建議用 transform: translateZ(0) 開啟 GPU 加速或改用 JS 視差。

結語:熟練掌握 background 簡寫,能大幅減少 CSS 行數,並集中管理視覺樣式。建議在專案中建立 .bg-* 工具類別,封裝常用背景模式,提升團隊協作一致性。

copyright © 萬盛學電腦網 all rights reserved