問題
首先是一個 div 塊里需要一張背景,帶文本和圖案的那種,但是身為容器的 div 是能夠隨數據的改變而變化長度的,所以一張靜態圖片不免的會有拉伸和擠扁的狀態,尤其是有圖案和文本的情況下最為明顯
.bg {
position: fixed;
top: 0px;
left: 0;
width: 183px;
height: 1106px;
background: no-repeat center/183px 100% url("img/001.png");
}
當數據不夠的時候就是一個扁扁的樣子
.bg {
position: fixed;
top: 0px;
left: 0;
width: 183px;
height: 600px;
background: no-repeat center/183px 100% url("img/001.png");
}
這時候就是想辦法能夠讓圖自適應且還能看的過去,於是就出現將頭部變形比較明顯的文字圖案和底部顏色漸變分成,兩個簡單的解決方法。這樣頭部文字不動,顏色漸變進行拉伸就不那么明顯了。於是分成兩個 div,分別存放頭部和底部,但是總感覺這方法有些繁瑣,看了看文檔發現 background 可以設置多背景
//縮寫形式
.bg {
position: fixed;
top: 0px;
left: 0;
width: 175px;
height: 600px;
background: no-repeat center 114px/175px calc(100% - 114px) url("img/002.png"), no-repeat center top/175px 114px url("img/003.png");
}
//分寫形式
.bg {
position: fixed;
top: 0px;
left: 0;
width: 175px;
height: 600px;
/* background: no-repeat center 114px/175px calc(100% - 114px) url("img/002.png"), no-repeat center top/175px 114px url("img/003.png"); */
background: url("img/002.png"), url("img/003.png");
background-repeat: no-repeat, no-repeat;
background-position: center 114px, center top;
background-size: 175px calc(100% - 114px), 175px 114px;
}
IE8 及更早的瀏覽器版本不支持一個元素有多個背景圖片
background 語法
背景縮寫屬性可以在一個聲明中設置所有的背景屬性
可以設置的屬性分別是:background-color, background-position, background-size, background-repeat, background-origin, background-clip, background-attachment,和 background-image 中間有些值缺少一兩個,並沒有什么問題
當然也可以分開寫屬性,比如下列屬性,個人更喜歡分寫屬性
- background-color 指定要使用的背景顏色
- background-position 指定背景圖像的位置
- background-size 指定背景圖片的大小
- background-repeat 指定如何重復背景圖像
- background-origin 指定背景圖像的定位區域
- background-clip 指定背景圖像的繪畫區域
- background-attachment 設置背景圖像是否固定或者隨着頁面的其余部分滾動
- background-image 指定要使用的一個或多個背景圖像
background-position
background-position 屬性設置背景圖像的起始位置
值 | 描述 |
---|---|
left top center bottom right | 如果僅指定一個關鍵字,其他值將會是"center" |
x% y% | 第一個值是水平位置,第二個值是垂直。左上角是 0%0%。右下角是 100%100%。如果僅指定了一個值,其他值將是 50%。默認值為:0%0% |
xpos ypos | 第一個值是水平位置,第二個值是垂直。左上角是 0。單位可以是像素(0px0px)或任何其他 CSS 單位。如果僅指定了一個值,其他值將是 50%。你可以混合使用%和 positions |
inherit | 指定 background-position 屬性設置應該從父元素繼承 |
css3 的 calc 函數
calc() 函數用於動態計算長度值
- 運算符前后都需要保留一個空格,width: calc(100% - 10px)
- 任何長度值都可以使用 calc()函數進行計算
- calc()函數支持 "+", "-", "*", "/" 運算
- calc()函數使用標准的數學運算優先級規則