经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » HTML/CSS » CSS » 查看文章
background-position百分比原理详解_CSS教程_CSS
来源:jb51  时间:2021/5/10 8:46:22  对本文有异议

今天帮别人调代码时,看到一个样式:

  1. background-position: 50% 0;
  2. background-size: 100% auto

对background-size:100% auto,意思是背景图片宽度为元素宽度*100%,高度等比缩放。详情可见css3 background

对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%呢?

二、background-position百分比计算公式

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

有了这个公式,就很容易理解百分百写法了,推算一下也就很容易理解上面各类等价写法了。

三、举例

1、background-position:center center等价于background-position:50% 50%等价于background-position:?px ?px

例子中用到背景图如下【尺寸:200px*200px】:

背景图在容器中居中。

  1. <style type="text/css">
  2. .wrap{
  3. width: 300px;
  4. height: 300px;
  5. border:1px solid green;
  6. background-image: url(img/image.png);
  7. background-repeat: no-repeat;
  8. /* background-position: 50% 50%;*/
  9. background-position: center center;
  10. }
  11. </style>
  12. <div class="wrap">
  13. </div>

效果都是让背景图片居中

如上通过设置百分比和关键字能实现背景图居中,如果要实现通过具体值来设置图片居中该设置多少?

根据上面公式:

x=(容器的宽度-背景图宽度)*x百分比=(300px-200px)*50%=50px;

y=(容器的高度-背景图高度)*y百分比=(300px-200px)*50%=50px;

即设置background-postion:50px 50px;

测试一下:

  1. <style type="text/css">
  2. .wrap{
  3. width: 300px;
  4. height: 300px;
  5. border:1px solid green;
  6. background-image: url(img/image.png);
  7. background-repeat: no-repeat;
  8. /* background-position: 50% 50%;*/
  9. /* background-position: center center;*/
  10. background-position: 50px 50px;
  11. }
  12. </style>
  13. <div class="wrap">
  14. </div>

效果同样居中。

到此这篇关于background-position百分比原理详解的文章就介绍到这了,更多相关background-position 百分比内容请搜索w3xue以前的文章或继续浏览下面的相关文章,希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号