DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> WEB網站前端 >> WEB前端代碼
網頁背景圖固定不動、不隨捲動條捲動的做法
編輯:WEB前端代碼     

當頁面使用一張完整的背景圖時,我們往往希望它固定在視窗上,捲動內容時背景紋絲不動。要做到這件事,得先認識 CSS 的幾個 background 屬性,最後再由 background-attachment 或 background 簡寫完成固定效果。

background-color:設定背景色

<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>

background-image:設定背景圖片

<body style="background-image:url(../images/css_tutorials/background.jpg)">
 <p>這個 HTML 使用了 CSS 的 background-image 屬性,設置了背景圖片。</p>
</body>

background-repeat:控制重複方式

body {
 background-image:url(../images/css_tutorials/background.jpg);
 background-repeat:repeat-y;
}

常用值有 repeat-x(橫向重複)、repeat-y(縱向重複)、no-repeat(不重複)與 repeat(預設的雙向重複)。此屬性需與 background-image 一起使用才有意義。

background-attachment:重點就在這裡

body {
 background-image:url(../images/css_tutorials/background.jpg);
 background-repeat:no-repeat;
 background-attachment:fixed;
}

background-attachment 有兩個值:

  • scroll:背景會隨內容一起捲動,這是預設值。
  • fixed:背景固定不動,不受內容捲動影響。

只要把這個屬性設為 fixed,就能得到「背景不動、內容在上面跑」的效果,一樣需要與 background-image 搭配使用。

background-position:決定起始位置

body {
 background-image:url(../images/css_tutorials/background.jpg);
 background-repeat:no-repeat;
 background-position:20px 60px;
}

上面的寫法代表背景圖的初始位置距頁面左側 20px、距頂部 60px。它必須和 background-image 連用,且若圖片要重複,會從這個點開始鋪排。

background:一行搞定全部設定

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 的獨立層,或搭配正规的視差捲動函式庫處理。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved