css中的百分比计算方法

来源:互联网 发布:破壁机原理 知乎 编辑:程序博客网 时间:2024/05/21 06:39

本文内容来源于http://www.ido321.com/1640.html 

CSS支持多种单位形式,如百分比、px、pt、rem等,百分比和px是常用的单位,随着移动端和响应式的流行,rem、vh、vw也开始普遍使用。

今天在SegmentFault社区碰到了两个关于百分比计算的问题,一个是在translate中使用百分比的时候,是相对于哪个DOM元素的大小计算的;另外一个是在paddingmargin等中使用百分比时,百分比又是怎么转为px的呢?

对于第一个,移动距离是根据自身元素的大小来计算的:

[The percentage] refer[s] to the size of the element’s box

例如:在不知道元素的宽度和高度的情况下,让元素水平垂直居中

创建类名为wrapper的div,并设置其样式

.wrapper {  padding: 20px;  background:orange;  color:#fff;  position:absolute;  top:50%;  left:50%;  border-radius: 5px;  -webkit-transform:translate(-50%,-50%);  -moz-transform:translate(-50%,-50%);  transform:translate(-50%,-50%);}


对于第二个,我认为percentage转px应该是浏览器根据css规定来完成的,但是具体怎么算呢?

Example 1: Margins

    1. <div style="width: 20px">
    2. <div id="temp1" style="margin-top: 50%">Test top</div>
    3. <div id="temp2" style="margin-right: 25%">Test right</div>
    4. <div id="temp3" style="margin-bottom: 75%">Test bottom</div>
    5. <div id="temp4" style="margin-left: 100%">Test left</div>
    6. </div>

得到的offset如下:

    1. temp1.marginTop = 20px * 50% = 10px;
    2. temp2.marginRight = 20px * 25% = 5px;
    3. temp3.marginBottom = 20px * 75% = 15px;
    4. temp4.marginLeft = 20px * 100% = 20px;

然后,我又测试了padding,原以为padding的值会根据应用了该属性的相关元素来计算,但让我惊讶的是,padding也是根据应用该属性的父元素的宽来计算的,跟margin表现一致。(再插一句:当按百分比设定一个元素的宽度时,它是相对于父容器的宽度计算的,元素竖向的百分比设定也是相对于容器的宽度,而不是高度。)

但有一个坑,上面都是对于未定位元素。好奇的我又很好奇,对于非静态定位元素的toprightbottom, 和left的百分比值又怎么计算呢?

Example 2: Positioned Elements

    1. <div style="height: 100px; width: 50px">
    2. <div id="temp1" style="position: relative; top: 50%">Test top</div>
    3. <div id="temp2" style="position: relative; right: 25%">Test right</div>
    4. <div id="temp3" style="position: relative; bottom: 75%">Test bottom</div>
    5. <div id="temp4" style="position: relative; left: 100%">Test left</div>
    6. </div>

得到的offset如下:

    1. temp1.top = 100px * 50% = 50px;
    2. temp2.right = 100px * 25% = 25px;
    3. temp3.bottom = 100px * 75% = 75px;
    4. temp4.left = 100px * 100% = 100px;

对于定位元素,这些值也是相对于父元素的,但与非定位元素不同的是,它们是相对于父元素的高而不是宽。

when the parent element does not have a height, then percentage values are processed as auto instead

虽然有点困惑,但只需要记住:对于marginpadding,百分比按照父元素的宽计算,对于定位元素,则按照父元素的高计算。


0 0
原创粉丝点击