萬盛學電腦網

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

CSS 網頁背景完整控制:顏色、圖片、重複、定位、固定與簡寫

CSS Background 全屬性精通:從單一屬性到背景簡寫大師

背景屬性是頁面視覺基調的關鍵。本文系統講解 background-color、background-image、background-repeat、background-position、background-attachment 及綜合簡寫,附最佳實踐與陷阱提醒。

1. 背景顏色 background-color

body { background-color: yellow; }
h1   { background-color: #000; }  /* 十六進位 */
.section { background-color: rgb(255,255,255); } /* RGB */

預設 transparent。建議同時設定背景色作為圖片載入失敗時的保底。

2. 背景圖片 background-image

body { background-image: url('../images/bg.png'); }
h1   { background-image: none; }  /* 明確關閉繼承圖片 */

預設 none。路徑相對 CSS 檔案位置。

3. 重複模式 background-repeat

值行為
repeat水平垂直雙向平鋪(預設)
repeat-x僅水平平鋪
repeat-y僅垂直平鋪
no-repeat不平鋪,單張顯示
space平鋪並均勻分佈空白(CSS3)
round平鋪並縮放填滿無縫隙(CSS3)

4. 定位 background-position

  • 關鍵字:left/center/right + top/center/bottom(如 center center、right bottom)。
  • 百分比:50% 50% 為中心,0% 0% 為左上角。
  • 長度值:100px 10px 相對左上角偏移。
  • 單一值:第二值預設 50%(垂直置中)。
  • 負值:允許圖片超出邊界。

5. 捲動行為 background-attachment

  • scroll(預設):隨頁面捲動。
  • fixed:固定於視口,視差效果基礎。
  • local:隨元素內容捲動(CSS3)。

6. 綜合簡寫 background(順序不嚴格,建議統一)

/* 推薦順序:color image repeat position attachment */
body {
  background: #f5f5f5 url('../images/bg.png') no-repeat center top fixed;
}
/* 等效展開 */
background-color: #f5f5f5;
background-image: url('../images/bg.png');
background-repeat: no-repeat;
background-position: center top;
background-attachment: fixed;

關鍵提醒: 背景色必須寫在最前或最後,不可夾在圖片 URL 之後,否則圖片可能不顯示。

7. 多重背景(CSS3)

.multi-bg {
  background: 
    url('pattern.png') repeat 0 0,
    url('hero.jpg') no-repeat center center,
    linear-gradient(45deg, #fff, #f0f0f0);
}

逗號分隔,第一層最上層。漸層視為背景圖片一種。

8. 效能與無障礙建議

  • 大圖使用 background-attachment: fixed 可能導致捲動卡頓,移動端慎用。
  • 圖片優化:WebP 格式、適當壓縮、響應式圖片 image-set()。
  • 文字對比度:確保背景圖上文字符合 WCAG AA (4.5:1) 對比度,必要時加半透明遮罩層。

精通背景屬性組合,能以最少代碼創造豐富視覺層次,並兼顧效能與無障礙。

copyright © 萬盛學電腦網 all rights reserved