<body>
<img id="bg" src="../images/bg.jpg"
width="100%" height="100%"
style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: -1;" />
...頁面內容...
</body>
position: fixed:相對視窗定位,不隨頁面捲動。top/left/right/bottom: 0:四邊貼齊視窗邊緣。width/height: 100%:撐滿整個視窗。z-index: -1:置於所有內容底層。body {
background: url('../images/bg.jpg') center center / cover no-repeat fixed;
/* background-size: cover 保證圖片填滿且保持比例 */
/* background-attachment: fixed 產生視差感(可選) */
}
優點:無額外 DOM、效能更好、支援響應式、可搭配多重背景、漸層疊加。
若需在小螢幕載入較小圖片,可用 @media 配合 image-set() 或 <picture> 元素實現美術導向適配。