Home » CSS

固定背景圖片及位置

蠻常見到有人問說,要如何才能讓背景圖片不管捲軸拉到那邊都不會變?這其實只要透過設定 background-attachment 就能達到該效果了。

Body其實並不用做任何設定,這邊我為了讓網頁有捲軸,所以在pre包起一段話:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<body>
<pre>
歡
 
迎
 
來
 
到
 
男
 
丁
 
格
 
爾's
 
脫
 
殼
 
玩
 
,
 
若
 
有
 
任
 
何
 
問
 
題
 
還
 
請
 
多
 
留
 
言
 
指
 
教
 
了
</pre >
</body>

接著來看CSS中的語法:

1
2
3
4
5
6
7
8
body{
	/* 設定背景圖片 */
	background-image:url("sakuya_and_remi.jpg");
	/* 讓圖片不重覆排列 */
	background-repeat:no-repeat;
	/* 固定背景圖片位置 */
	background-attachment:fixed;
}

只要把 background-attachment 設成 fixed 就能固定背景圖片了。若是要取消固定的話,只要把 background-attachment 拿掉或是設成 none 就行了。而其中的 background-repeat 設成 no-repeat 是避免當背景圖片太小張時,讓它不要重覆的顯示。

還有另一種常見的情況是,背景圖片本身就只是小小張的,但想讓它固定在網頁的某一位置的話,我們除了用 background-attachment 之外,還要搭配 background-position 來一起使用。

Body一樣不變,直接看CSS的部份:

1
2
3
4
5
6
7
8
9
10
body{
	/* 設定背景圖片 */
	background-image:url("logo.gif");
	/* 讓圖片不重覆排列 */
	background-repeat:no-repeat;
	/* 固定背景圖片位置 */
	background-attachment:fixed;
	/* 設定背景圖片在右下角 */
	background-position:right bottom;
}

background-position 值的設定可用數字加單位、數字加百分比或是使用關鍵字。background-position 基本上需要兩各值,第一個是距離左邊界的值,另一個則是距離上邊界的值。但是若是要在中間的話,可以設一個 center 就可以了,另一個若沒有的話,會自動認為也是 center

background-position 位置的相對關係可以參考下面的圖解。

固定背景圖片及位置-1

怎樣~是不是很簡單呢!

範例瀏覽:
http://demonstration.abgne.tw/css/0001/0001_1.html
http://demonstration.abgne.tw/css/0001/0001_2.html

[ 標籤: ]

2 筆針對 固定背景圖片及位置 的迴響

發表迴響