在 CSS 中,背景附件屬性 background-attachment 用來決定背景圖像是跟著內容一起滾動,還是固定在原地不動。
語法:
background-attachment:scroll/fixed;
說明:
這個屬性只有兩個取值。scroll 表示背景圖像隨元素內容一起滾動,是預設選項;fixed 表示背景圖像固定在頁面上不動,只有其他內容隨滾動條移動。
舉例:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>background-attachment屬性</title>
<style type="text/css">
#div1 { width:160px; height:1200px; border:1px solid gray; background-image:url("../App_images/lesson/run_cj/cartoongirl.gif"); background-repeat:no-repeat; background-attachment:fixed; }
</style>
</head>
<body>
<div id="div1"></div>
</body>
</html>
在瀏覽器中預覽,效果如下:
分析:
在瀏覽器中拖動右側滾動條會發現,背景圖片釘在視窗內紋絲不動,而方塊本身隨頁面滾動。
這裡有個相容性提醒:在 IE 或 360 瀏覽器中設定了 background-attachment 之後,如果再設定 background-position,圖片可能無法正常顯示。建議同時用 Chrome、Firefox 測試對照。