在網頁設計中,常會希望背景圖片固定在畫面中央,當內容捲動時背景不跟著移動。最直接的方式是使用 background-attachment: fixed;。
可以將背景圖片設定在 body 或其他容器上,例如使用一張背景圖:https://hovertree.com/hvtimg/bjafjc/wpirf7t5.png。
概念如下:
body {
background-image: url('https://hovertree.com/hvtimg/bjafjc/wpirf7t5.png');
background-attachment: fixed;
}
這樣設定後,當頁面其他內容捲動時,背景圖片會保持固定。
需要注意的是,background-attachment: fixed; 在部分手機瀏覽器中可能出現相容性問題。此時可以改用偽元素建立固定層,再將背景圖放在該層上。
例如可使用另一張背景圖:https://hovertree.com/hvtimg/bjafaj/hm1uwx31.jpg,概念如下:
body::before {
content: ' ';
position: fixed;
z-index: -1;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: url('https://hovertree.com/hvtimg/bjafaj/hm1uwx31.jpg') top center no-repeat;
background-size: cover;
}
這種做法能讓背景層固定在視窗上,同時避免部分行動裝置對 fixed 背景支援不佳的問題。