標籤:
原文連結:http://caibaojian.com/background-position-percent.html
background-position: 50% 0;background-size: 100% auto;
via對background-size:100% auto,意思是背景圖片寬度為元素寬度*100%,高度等比縮放。詳情可見css3 background。原文來自:http://caibaojian.com/background-position-percent.html
對background-position很自然的以為百分比是根據父元素寬度計算的,但background-position真的不是,它有一套自己的原理。下面詳細介紹。
等價寫法
在看各類教程時有以下等價寫法:
- top left, left top 等價於 0% 0%.
- top, top center, center top 等價於 50% 0%.
- right top, top right 等價於 100% 0%.
- left, left center, center left 等價於 0% 50%.
- center, center center 等價於 50% 50%.
- right, right center, center right 等價於 100% 50%.
- bottom left, left bottom 等價於 0% 100%.
- bottom, bottom center, center bottom 等價於 50% 100%.
- bottom right, right bottom 等價於 100% 100%.
那麼為什麼left,top就等價於0% 0%,right bottom等價於100% 100%呢?
百分比計算公式
任何CSS屬性值為percent時,都需要根據某個參考值進行計算,搞明白這個參考值是什麼,理解就容易多了。
標準規定:background-position:perenct的參考值為: (容器寬度 - 背景圖片寬度).
//code from http://caibaojian.com/background-position-percent.htmlbackground-postion:x y;x:{容器(container)的寬度—背景圖片的寬度}*x百分比,超出的部分隱藏。y:{容器(container)的高度—背景圖片的高度}*y百分比,超出的部分隱藏。
有了這個公式,就很容易理解百分百寫法了,推算一下也就很容易理解上面各類等價寫法了。
舉例
1、background-position:center center等價於background-position:50% 50%等價於background-position:?px ?px
例子中用到背景圖如下【尺寸:200px*200px】:
背景圖在容器中置中。
<style type="text/css">.wrap{ width: 300px; height: 300px; border:1px solid green; background-image: url(img/image.png); background-repeat: no-repeat;/* background-position: 50% 50%;*/ background-position: center center;}</style><div class="wrap"></div>
效果都是讓背景圖片置中
如上通過設定百分比和關鍵字能實現背景圖置中,如果要實現通過具體值來設定圖片置中該設定多少?
根據上面公式:
x=(容器的寬度-背景圖寬度)*x百分比=(300px-200px)*50%=50px;
y=(容器的高度-背景圖高度)*y百分比=(300px-200px)*50%=50px;
即設定background-postion:50px 50px;
測試一下:
<style type="text/css">.wrap{ width: 300px; height: 300px; border:1px solid green; background-image: url(img/image.png); background-repeat: no-repeat;/* background-position: 50% 50%;*//* background-position: center center;*/ background-position: 50px 50px;}</style><div class="wrap"></div>
效果同樣置中。
推算百分比:
從上面看出來,百分比為background-position-x的值 = (背景在雪碧中的左邊寬度)/(容器寬度 - 背景圖片寬度)*100%。
平常使用 background-position,一般是用固定值,比如:
.hello { background-position: 50px 50px; // 背景圖片左上方離包含塊左上方距離為水平方向 50px,豎直方向 50px}
那如果上面的固定值 50px,我堅持要寫成百分比如何?
已知背景圖片大小為 150×150,包含塊大小為 200×200。
答案是:
.hello { background-position: 100% 100%;}
這個值是這樣計算的:
50/(200-150)*100% = 100%
這是因為 background-position 在使用百分比時,概念跟固定取值並不一樣。
舉上面的樣本說,如果設定 background-postion:10% 30%;,則是背景圖片水平方向 10% 位置的點與包含塊水平方向 10% 位置的點重合。換算成固定取值的話:
(200-50)*10% = 5
示意如下:
但如果我們使用負的百分比,則瀏覽器的處理方式又跟絕對值一樣了,比如:
.test { background-position: -10%, -50%;}
就是讓背景圖片起點定位到包含塊 (-10%, -50%) 的位置。
這個概念不十分直觀,所以沒細究的話,很容易誤解。
在rem中的應用
在使用自適應時,由於數位誤差導致了背景圖片會出現定位出現一些小偏差問題,如果可以將背景圖片通過百分比來定位,而不是預設的rem來定位,可能精準度更高點。
css3背景圖片百分比