當頁面使用一張完整的背景圖時,我們往往希望它固定在視窗上,捲動內容時背景紋絲不動。要做到這件事,得先認識 CSS 的幾個 background 屬性,最後再由 background-attachment 或 background 簡寫完成固定效果。
<html> <head> <title>背景顏色 background-color</title>
<style type="text/css"> body {background-color:#99FF00;} </style> </head>
<body> <p>這個 HTML 使用了 CSS 的 background-color 屬性,將背景顏色變成翠綠色。</p> </body> </html>
<body style="background-image:url(../images/css_tutorials/background.jpg)">
<p>這個 HTML 使用了 CSS 的 background-image 屬性,設置了背景圖片。</p>
</body>
body {
background-image:url(../images/css_tutorials/background.jpg);
background-repeat:repeat-y;
}
常用值有 repeat-x(橫向重複)、repeat-y(縱向重複)、no-repeat(不重複)與 repeat(預設的雙向重複)。此屬性需與 background-image 一起使用才有意義。
body {
background-image:url(../images/css_tutorials/background.jpg);
background-repeat:no-repeat;
background-attachment:fixed;
}
background-attachment 有兩個值:
只要把這個屬性設為 fixed,就能得到「背景不動、內容在上面跑」的效果,一樣需要與 background-image 搭配使用。
body {
background-image:url(../images/css_tutorials/background.jpg);
background-repeat:no-repeat;
background-position:20px 60px;
}
上面的寫法代表背景圖的初始位置距頁面左側 20px、距頂部 60px。它必須和 background-image 連用,且若圖片要重複,會從這個點開始鋪排。
body {
background:#99FF00 url(../images/css_tutorials/background.jpg) no-repeat fixed 40px 100px;
}
這是背景相關屬性的綜合簡寫,依序涵蓋 background-color、background-image、background-repeat、background-attachment 與 background-position。以上面這行為例,意思是:背景色為翠綠色、背景圖為 background.jpg、不重複、不隨內容捲動、距左側 40px、距頂部 100px。
實務小提醒:background-attachment:fixed 在手機 Safari 等行動瀏覽器上支援度不佳,若要在行動裝置上做出視差或固定背景,通常得改用 position:fixed 的獨立層,或搭配正规的視差捲動函式庫處理。