案例:
background-size:100% auto,意思是背景图片宽度为元素宽度*100%,高度等比缩放。详情可见css3 background。
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.html background-postion:x y; x:{容器(container)的宽度—背景图片的宽度}*x百分比,超出的部分隐藏。 y:{容器(container)的高度—背景图片的高度}*y百分比,超出的部分隐藏。
有了这个公式,就很容易理解百分百写法了,推算一下也就很容易理解上面各类等价写法了 类似于以下处理
background-position:center center等价于background-position:50% 50%等价于background-position:?px ?px
示例:
背景图在容器中居中
<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>
在rem中的应用
在使用自适应时,由于数字的误差导致了背景图片会出现定位出现一些小偏差问题,如果可以将背景图片通过百分比来定位,而不是默认的rem来定位,可能精准度更高点
示例:
HTML
<div class="m-shareBox" id="Jbdshare_wrap">
<p class="p_tit">分享到</p>
<div id="bdshare" class="bdshare_t bds_tools get-codes-bdshare">
<a class="bds_tsina" title="分享到新浪微博" href="#">新浪微博</a>
<a class="bds_tqq" title="分享到腾讯微博" href="#">腾讯微博</a>
<a class="bds_qzone" title="分享到QQ空间" href="#">QQ空间</a>
<a class="bds_weixin" title="分享到微信" href="#">微信</a>
</div>
</div>
CSS代码
.m-shareBox .bdshare_t a:before{display:block; content:""; background:url(img/bdshare.png) no-repeat; background-size:cover; width:.72rem; height:.72rem; margin:0 auto .11rem;}
.m-shareBox .bdshare_t .bds_tsina:before{background-position:center 0;}
.m-shareBox .bdshare_t .bds_tqq:before{background-position:center 25%;}
.m-shareBox .bdshare_t .bds_qzone:before{background-position:center 50%;}
.m-shareBox .bdshare_t .bds_weixin:before{background-position:center 75%;}