今天幫別人調代碼時,看到一個樣式:css
background-position: 50% 0;
background-size: 100% auto;
對background-size:100% auto,意思是背景圖片寬度爲元素寬度*100%,高度等比縮放。詳情可見css3 background。html
對background-position很天然的覺得百分比是根據父元素寬度計算的,但background-position真的不是,它有一套本身的原理。下面詳細介紹。css3
在看各種教程時有如下等價寫法:post
那麼爲何left,top就等價於0% 0%,right bottom等價於100% 100%呢?測試
background-postion:x y; x:{容器(container)的寬度—背景圖片的寬度}*x百分比,超出的部分隱藏。 y:{容器(container)的高度—背景圖片的高度}*y百分比,超出的部分隱藏。
有了這個公式,就很容易理解百分百寫法了,推算一下也就很容易理解上面各種等價寫法了。url
一、background-position:center center等價於background-position:50% 50%等價於background-position:?px ?px3d
例子中用到背景圖以下【尺寸:200px*200px】:htm
背景圖在容器中居中。blog
<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>
效果一樣居中。