css background-attachment屬性進(jìn)階

前提是定義了background-image屬性,然后用background-attachment來指明背景圖的位置是固定于視口的,還是隨著包含塊移動的??珊唵卫斫鉃槎x背景圖片隨滾動軸的移動方式。
取值:
scroll:默認(rèn)值,背景圖相對于元素固定,背景隨頁面滾動而移動,即背景和內(nèi)容綁定。
fixed:背景圖相對于視口固定,所以隨頁面滾動背景不動,相當(dāng)于背景被設(shè)置在了body上。
local:背景圖相對于元素內(nèi)容固定,
inhert:繼承,沒什么說的。
該屬性可以應(yīng)用于任何元素。
一、scroll【背景圖滾動】
設(shè)置background-attachment:scroll,背景圖是相對于元素自身固定,內(nèi)容動時背景圖也動。附加到元素的border。

local
Note:
對于scroll,一般情況背景隨內(nèi)容滾動,但是有一種情況例外。
對于可以滾動的元素(設(shè)置為overflow:scroll的元素)。當(dāng)background-attachment設(shè)置為scroll時,背景圖不會隨元素內(nèi)容的滾動而滾動。

二、local【滾動元素背景圖滾動】
對于可以滾動的元素(設(shè)置為overflow:scroll的元素),設(shè)置background-attachment:local,則背景會隨內(nèi)容的滾動而滾動。
因為背景圖是相對于元素自身內(nèi)容定位,開始固定,元素出現(xiàn)滾動條后背景圖隨內(nèi)容而滾動。
<style> div{ width: 200px; height: 350px; border: 1px solid red; background-image: url(img/img_tree.png); background-repeat: no-repeat; background-attachment: local; overflow: scroll; line-height: 1.5; } </style> <body> <div> 1內(nèi)容超出會出現(xiàn)滾動條 2內(nèi)容超出會出現(xiàn)滾動條 3內(nèi)容超出會出現(xiàn)滾動條 4內(nèi)容超出會出現(xiàn)滾動條 5內(nèi)容超出會出現(xiàn)滾動條 6內(nèi)容超出會出現(xiàn)滾動條 7內(nèi)容超出會出現(xiàn)滾動條 8內(nèi)容超出會出現(xiàn)滾動條 9內(nèi)容超出會出現(xiàn)滾動條 10內(nèi)容超出會出現(xiàn)滾動條 11內(nèi)容超出會出現(xiàn)滾動條 12內(nèi)容超出會出現(xiàn)滾動條 13內(nèi)容超出會出現(xiàn)滾動條 14內(nèi)容超出會出現(xiàn)滾動條 15內(nèi)容超出會出現(xiàn)滾動條 16內(nèi)容超出會出現(xiàn)滾動條 17內(nèi)容超出會出現(xiàn)滾動條 18內(nèi)容超出會出現(xiàn)滾動條 19內(nèi)容超出會出現(xiàn)滾動條 20內(nèi)容超出會出現(xiàn)滾動條 </div> </body>
三、fixed:【背景圖靜止】
背景圖片相對于視口固定,就算元素有了滾動條,背景圖也不隨內(nèi)容移動。
fixed用法如下:
<style> body{ background-image: url(img/cartooncat.png); background-position: bottom left; background-attachment: fixed; background-repeat: no-repeat; height: 1000px; } </style> </head> <body> <h1>下拉看效果:</h1> </body>
或者看mozilla的demo。
這里我要強調(diào)一點我的看法:
給任何元素的背景圖設(shè)置background-attachment: fixed;效果都是一樣的,都是相對于視口,因為一個網(wǎng)頁只有一個視口,該背景和元素已經(jīng)沒關(guān)系了,要說有關(guān)大概也只是元素不可見則背景圖不可見。
而這個視口是什么呢?這里推薦一篇文章《像素與瀏覽器視口的細(xì)節(jié)》
四、多背景圖background-attachment
也可以為多個背景圖設(shè)置background-attachment
body { background-image: url("img1.png"), url("img2.png"); background-attachment: scroll, fixed; }
五、資源鏈接
相關(guān)文章
css 背景固定樣式background-attachment屬性基礎(chǔ)
這篇文章主要為大家介紹了在CSS中,使用背景附件屬性background-attachment可以設(shè)置背景圖像是隨對象滾動還是固定不動,需要的朋友可以參考下2017-03-08關(guān)于css中的 background-attachment 屬性詳解
這篇文章主要介紹了關(guān)于css中的 background-attachment 屬性詳解,在日常的使用中,還是background-attachment:fixed 使用的最多,因為這個屬性更多的時候是跟background-im2023-10-10