.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; /* 預設,隨頁面捲動 */
}
<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;
}
<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>
<link rel="preload" as="image" href="hero.jpg">。loading="lazy" 或 IntersectionObserver 動態載入。contain: layout paint style; 限制重繪範圍。| 問題 | 原因 | 解法 |
|---|---|---|
| 白邊/未滿版 | 背景定位/尺寸錯誤 | 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 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 方案。