萬盛學電腦網

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

CSS 全螢幕背景圖片實現:Cover、Fixed、Responsive、Performance 最佳實踐

核心需求

  • 圖片填滿整個視口(無白邊)。
  • 保持原始比例(不變形)。
  • 支援響應式(不同螢幕尺寸自動適配)。
  • 效能優化:適當尺寸、格式、載入策略。

現代標準寫法(推薦)

.fullscreen-bg {
  position: fixed;
  inset: 0;                    /* top:0; right:0; bottom:0; left:0; */
  z-index: -1;                 /* 置於內容之下 */
  background: url(hero.jpg) center / cover no-repeat;
  /* 等同於:
  background-image: url(hero.jpg);
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: scroll; /* 預設,隨頁面捲動 */
}

HTML 結構

<body>
  <div class="fullscreen-bg" aria-hidden="true"></div>
  <main>頁面內容</main>
</body>

進階變體

固定背景視差效果

.parallax-bg {
  position: fixed;
  inset: 0;
  z-index: -1;
  background: url(hero.jpg) center / cover no-repeat;
  background-attachment: fixed;  /* 關鍵:背景相對視口固定 */
}

注意:移動端 background-attachment: fixed 效能差、行為不一(iOS 早期不支援),建議用 transform: translateZ(0) 強制合成層或改用 JS 視差庫。

多層背景漸層疊加

.hero-bg {
  position: fixed;
  inset: 0;
  z-index: -1;
  background:
    linear-gradient(135deg, rgba(30,136,229,0.8), rgba(0,0,0,0.6)),
    url(hero.jpg) center / cover no-repeat;
}

響應式多尺寸圖片(Art Direction)

<picture>
  <source media="(max-width: 480px)" srcset="hero-mobile.jpg">
  <source media="(max-width: 1024px)" srcset="hero-tablet.jpg">
  <img src="hero-desktop.jpg" class="fullscreen-bg" alt="" aria-hidden="true">
</picture>

效能優化清單

  1. 圖片壓縮:WebP/AVIF 格式、適當品質(75-85)、移除 EXIF。
  2. 多尺寸生成:構建工具自動產出 400/800/1200/1600/2000w 版本。
  3. 預載關鍵圖片:<link rel="preload" as="image" href="hero.jpg">。
  4. Lazy Loading 非首屏:非 Hero 區塊背景圖用 loading="lazy" 或 IntersectionObserver 動態載入。
  5. CSS containment:contain: layout paint style; 限制重繪範圍。
  6. 避免巨大 Base64 內聯:增加 CSS 體積、阻塞渲染、無法快取。

常見坑點與解法

問題原因解法
白邊/未滿版背景定位/尺寸錯誤center / cover、確認容器 inset:0
圖片變形用 100% 100% 而非 cover改用 cover 或 contain
捲動時背景抖動fixed 合成層問題改 scroll 或 transform: translateZ(0)
移動端 fixed 失效瀏覽器優化禁用改用 position: sticky + 偽元素或 JS 視差
z-index 遮蔽內容層級過高背景層 z-index: -1 或 0,內容層 > 0

替代方案:<img> + object-fit

<img src="hero.jpg" alt="" aria-hidden="true"
     style="position:fixed; inset:0; width:100%; height:100%; object-fit:cover; z-index:-1;">
  • 語意更清晰(圖片即內容)、支援 srcset/sizes 響應式、可被搜尋引擎索引。
  • 缺點:無法像 background 那樣疊加多層漸層/裝飾。

總結

全螢幕背景圖片的現代標準解:position:fixed; inset:0; background: url(...) center/cover no-repeat; z-index:-1。配合 picture+srcset 響應式、WebP/AVIF 格式、Preload 關鍵圖、Lazy Loading 非關鍵圖、contain 優化渲染。若需視差,評估移動端效能後謹慎使用 background-attachment:fixed 或改用 JS 方案。

copyright © 萬盛學電腦網 all rights reserved