css的background-attachment進階使用方法

來源:互聯網
上載者:User
這次給大家帶來css的background-attachment進階使用方法,使用css的background-attachment注意事項有哪些,下面就是實戰案例,一起來看一下。

前提是定義了background-image屬性,然後用background-attachment來指明背景圖的位置是固定於視口的,還是隨著包含塊移動的。可簡單理解為定義背景圖片隨捲軸的移動方式。
取值:
scroll:預設值,背景圖相對於元素固定,背景隨頁面滾動而移動,即背景和內容綁定。
fixed:背景圖相對於視口固定,所以隨頁面滾動背景不動,相當於背景被設定在了body上。
local:背景圖相對於元素內容固定,
inhert:繼承,沒什麼說的。
該屬性可以應用於任何元素。
一、scroll【背景圖滾動】
設定background-attachment:scroll,背景圖是相對於元素自身固定,內容動時背景圖也動。附加到元素的border。

local
Note:
對於scroll,一般情況背景隨內容滾動,但是有一種情況例外。
對於可以滾動的元素(設定為overflow:scroll的元素)。當background-attachment設定為scroll時,背景圖不會隨元素內容的滾動而滾動。

二、local【滾動元素背景圖滾動】
對於可以滾動的元素(設定為overflow:scroll的元素),設定background-attachment:local,則背景會隨內容的滾動而滾動。
因為背景圖是相對於元素自身內容定位,開始固定,元素出現捲軸後背景圖隨內容而滾動。

<style>p{    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>    <p>    1內容超出會出現捲軸    2內容超出會出現捲軸    3內容超出會出現捲軸    4內容超出會出現捲軸    5內容超出會出現捲軸    6內容超出會出現捲軸    7內容超出會出現捲軸    8內容超出會出現捲軸    9內容超出會出現捲軸    10內容超出會出現捲軸    11內容超出會出現捲軸    12內容超出會出現捲軸    13內容超出會出現捲軸    14內容超出會出現捲軸    15內容超出會出現捲軸    16內容超出會出現捲軸    17內容超出會出現捲軸    18內容超出會出現捲軸    19內容超出會出現捲軸    20內容超出會出現捲軸    </p></body>

三、fixed:【背景圖靜止】 背景圖片相對於視口固定,就算元素有了捲軸,背景圖也不隨內容移動。
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。

這裡我要強調一點我的看法:

給任何元素的背景圖設定background-attachment: fixed;效果都是一樣的,都是相對於視口,因為一個網頁只有一個視口,該背景和元素已經沒關係了,要說有關大概也只是元素不可見則背景圖不可見。

而這個視口是什麼呢?這裡推薦一篇文章《像素與瀏覽器視口的細節》

四、多背景圖background-attachment 也可以為多個背景圖設定background-attachment

body {  background-image: url("img1.png"), url("img2.png");  background-attachment: scroll, fixed;}

五、資源連結

w3c background-attachment

像素與瀏覽器視口的細節

a table of two viewports

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

CSS的background-attachment使用詳解

Bootstrap實現價格表

css中px、em和rem使用詳解

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.