萬盛學電腦網

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

CSS 設定 DIV 背景圖片完整屬性指南:路徑、平鋪、定位、尺寸、固定

前言

background 是 CSS 功能最豐富的屬性群。本文系統整理背景圖片的所有控制屬性,提供可直接套用的完整範例與最佳實踐。

一、單一背景完整屬性拆解

.box {
  width: 200px; height: 100px;
  border: 1px solid red; color: #fff;
  
  /* 核心屬性 */
  background-image: url("photo.gif");      /* 圖片路徑,建議加引號 */
  background-repeat: repeat-x;             /* 水平平鋪 */
  background-position: left top;           /* 起始位置 */
  background-attachment: scroll;           /* scroll 隨內容捲動 | fixed 固定視窗 */
  background-size: auto;                   /* auto 原尺寸 | cover 覆蓋 | contain 完整顯示 | 100% 100% 拉伸 */
  background-color: #f0f0f0;               /* 兜底色,圖片透明/未載入時顯示 */
  
  /* 縮寫(順序:color image repeat attachment position/size) */
  background: #f0f0f0 url("photo.gif") repeat-x scroll left top / auto;
}

二、屬性值完整對照表

屬性值範例說明
background-imageurl("img.png"), linear-gradient(...), none多背景用逗號分隔,第一層最上
background-repeatrepeat, repeat-x, repeat-y, no-repeat, space, roundspace 等間距平鋪, round 縮放填滿
background-positionleft top, center, right bottom, 10px 20px, 50% 50%關鍵字/長度/百分比,可單寫 X/Y
background-attachmentscroll, fixed, locallocal 隨元素內容捲動
background-sizeauto, cover, contain, 100% 100%, 200px 100px可用 背景尺寸/背景位置 寫在縮寫中
background-originpadding-box, border-box, content-box定位基準區域,預設 padding-box
background-clipborder-box, padding-box, content-box, text繪製裁切區域,text 可做文字遮罩

三、常見場景最佳實踐

1. 全螢幕英雄區

.hero {
  min-height: 100vh;
  background: url("hero.jpg") no-repeat center center / cover;
  /* 等同 background-size: cover; background-position: center; */
}

2. 固定背景視差效果

.parallax {
  height: 500px;
  background: url("bg.jpg") no-repeat center center / cover fixed;
  /* fixed 產生視差感,移動端可能有效能/顯示問題,建議媒體查詢關閉 */
}
@media (max-width: 768px) {
  .parallax { background-attachment: scroll; }
}

3. 圖片模糊佔位(LQIP)

.lazy-img {
  background: url("blur-placeholder.jpg") no-repeat center / cover;
  transition: background 0.3s;
}
.lazy-img.loaded { background-image: url("full-res.jpg"); }

4. CSS 圖片遮罩文字

.text-mask {
  background: url("texture.jpg") no-repeat center / cover;
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-size: 4rem; font-weight: bold;
}

四、路徑與相對位置注意事項

  • CSS 中 url() 路徑相對於 CSS 檔案位置,非 HTML 頁面。
  • 建議使用根相對路徑 /images/xxx.jpg 避免目錄層級變動失效。
  • url() 可不加引號,但含空格/特殊字元時必須加引號。

五、效能優化建議

  1. 優先使用 background-size: cover 避免圖片過大浪費頻寬。
  2. 關鍵背景圖預載入:<link rel="preload" as="image" href="hero.jpg">。
  3. 小圖標合併為 Sprite 或使用 SVG/Font Icon,減少請求。
  4. 適當啟用 background-attachment: fixed,移動端謹慎使用(重繪成本高)。

結語

背景圖片屬性看似繁多,掌握 image → repeat → position → attachment → size → origin → clip 七大維度,即可精準控制任何背景表現。現代開發建議:縮寫用於簡單場景,複雜多背景用拆解寫法,配合 CSS 變數管理主題路徑。

copyright © 萬盛學電腦網 all rights reserved