將背景圖固定於視口,不隨內容滾動,僅需一行 CSS:
.fixed-bg {
background-image: url(bg.jpg);
background-attachment: fixed;
background-position: center center;
background-repeat: no-repeat;
background-size: cover; /* 現代瀏覽器自適應覆蓋 */
}
<style>
html, body { height: 100%; margin: 0; }
.bg-layer {
position: fixed;
inset: 0;
background: #000 url(bg.jpg) center/cover no-repeat;
opacity: 0.5;
z-index: -1;
}
.content { position: relative; z-index: 1; }
</style>
<div class="bg-layer"></div>
<div class="content">頁面內容正常滾動,背景保持固定</div>
background-attachment: fixed 在 iOS Safari 早期版本有效能問題,建議改用 position: fixed 偽元素方案。filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(...) 但不推薦。