background-position百分比原理详解
今天帮别人调代码时,看到一个样式:
background-position: 50% 0; 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百分比计算公式
background-postion:x y; x:{容器(container)的宽度—背景图片的宽度}*x百分比,超出的部分隐藏。 y:{容器(container)的高度—背景图片的高度}*y百分比,超出的部分隐藏。
有了这个公式,就很容易理解百分百写法了,推算一下也就很容易理解上面各类等价写法了。
三、举例
1、background-position:center center等价于background-position:50% 50%等价于background-position:?px ?px
例子中用到背景图如下【尺寸:200px*200px】:
背景图在容器中居中。
<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>
效果同样居中。
到此这篇关于background-position百分比原理详解的文章就介绍到这了,更多相关background-position 百分比内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!
相关文章
探究background-position属性中的百分比值的使用
这篇文章主要介绍了探究background-position属性中的百分比值的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着2021-01-11CSS背景background、background-position使用详解
这篇文章主要介绍了CSS背景background、background-position使用方法,需要的朋友可以参考下2014-10-22css background-position 用法详细图文介绍
css background-position背景定位属性想必从事前端开发的朋友并不陌生吧,这个属性很实用的利用它可以实现很多的图片样式效果,下面是其具体的使用方法,感兴趣的朋友不要2013-11-04对背景图定位中background-position属性的自我理解
最近在项目中需要大量的用到很多标签按钮什么的零碎图片,加上一直没机会使用Css中的”精灵技术“,这里把我对background-position的理解写成文档供更多人使用学习;如果有2013-01-15CSS中背景background-position负值定位深入理解[图文]
CSS中背景定位background-position负值一直是不好理解的难点,一方面用的比较少,另一方面的理解的不够深入,今天花了点时间认真的思考了,把我的心得写出来2011-03-21利用CSS定位背景图片 background-position
我们在研究其他的网站的样式的时候经常会发现一种情况,就是在很多background属性里都调用同一张图片,来满足网页各个部分的使用。打开这种图片看一下,会发现这张图片上包2009-12-17CSS background-position的使用说明详解
设置或检索对象的背景图像位置。必须先指定 background-image 属性。该属性定位不受对象的补丁属性( padding )设置影响2009-12-17CSS background-position 属性 定位图片
看别人代码发现一个背景图中有很多图片,大家可以参考下原理2009-11-20
最新评论