码迷,mamicode.com
首页 > Web开发 > 详细

css 背景图片百分比

时间:2017-09-23 13:41:09      阅读:358      评论:0      收藏:0      [点我收藏+]

标签:lock   style   bottom   str   div   ott   logs   部分   ref   

1.等价写法

在看各类教程时有以下等价写法:·

  • 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%.

这是怎么换算的呢?

2.百分比计算公式

任何CSS属性值为percent时,都需要根据某个参考值进行计算,搞明白这个参考值是什么,理解就容易多了。·

标准规定:background-position:perenct的参考值为: (容器宽度 - 背景图片宽度).

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

有了这个公式,就很容易理解百分百写法了,同理如果是负的百分比呢?

background-position:-50% -50%;

等同于x:- {容器(container)的宽度—背景图片的宽度}*x百分比,超出的部分隐藏。
等同于y:- {容器(container)的高度—背景图片的高度}*y百分比,超出的部分隐藏。

3.推算百分比:

从上面看出来,百分比为:

background-position    x的值 = (背景图片左上角离包含块左上角距离)/(容器宽度 - 背景图片宽度)*100%。y的值同理可得。

平常使用 background-position,一般是用固定值,比如:

1 div {
2   background-position: 60px 10px; // 背景图片左上角离包含块左上角距离为水平方向 60px,竖直方向 10px
3 }

 那如果上面的固定值,我坚持要写成百分比如何?

已知背景图片大小为 450×250,包含块div大小为 600×300。

计算得:

x = 60/(600-450)*100%=40%

y = 10/(300-250)*100%=20%

答案是:

1 div {
2     background-position:40% 20%;
3 }

附上2个参考链接,写的很详细却也很复杂....

http://caibaojian.com/background-position-percent.html

http://www.cnblogs.com/zxx-foreve1130/p/3964243.html

css 背景图片百分比

标签:lock   style   bottom   str   div   ott   logs   部分   ref   

原文地址:http://www.cnblogs.com/smallyueliang/p/7580838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!