background-position百分比原理

今天幫別人調代碼時,看到一個樣式:css

background-position: 50% 0;
background-size: 100% auto;

對background-size:100% auto,意思是背景圖片寬度爲元素寬度*100%,高度等比縮放。詳情可見css3 backgroundhtml

對background-position很天然的覺得百分比是根據父元素寬度計算的,但background-position真的不是,它有一套本身的原理。下面詳細介紹。css3

1、等價寫法

在看各種教程時有如下等價寫法:post

  • 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%呢?測試

2、background-position百分比計算公式

background-postion:x y;
x:{容器(container)的寬度—背景圖片的寬度}*x百分比,超出的部分隱藏。
y:{容器(container)的高度—背景圖片的高度}*y百分比,超出的部分隱藏。

 有了這個公式,就很容易理解百分百寫法了,推算一下也就很容易理解上面各種等價寫法了。url

3、舉例

一、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>
複製代碼

效果一樣居中。

相關文章
相關標籤/搜索