CSS背景圖片固定方法
在CSS中,我們可以使用background-attachment
屬性來固定背景圖片,該屬性有三個(gè)值:scroll
、fixed
和local
。
scroll
背景圖片隨頁面滾動,這是默認(rèn)值。
fixed
背景圖片固定,不隨頁面滾動。
local
背景圖片隨元素內(nèi)容的滾動而滾動。
如果我們想要讓背景圖片固定不滾動,可以使用fixed
值。
body { background-image: url('image.jpg'); background-attachment: fixed; }
這樣,背景圖片就會固定在body元素上,不會隨頁面滾動。
我們還可以使用CSS的position
屬性來進(jìn)一步控制背景圖片的位置。
body { background-image: url('image.jpg'); background-attachment: fixed; position: relative; }
這樣,背景圖片就會相對于body元素進(jìn)行定位,可以使用top
、right
、bottom
和left
屬性來調(diào)整圖片的位置。
body { background-image: url('image.jpg'); background-attachment: fixed; position: relative; top: 0; right: 0; bottom: 0; left: 0; }
這樣,背景圖片就會完全覆蓋整個(gè)頁面,并且固定在頁面的中心位置。