三度网教程:是一个免费提供流行视频软件教程、在线学习分享的学习平台!

css支持的百分比计算方法

时间:2018-01-01作者:未知 来源:三度网教程人气:70

层叠样式表(英文全称:Cascading Style Sheets)是一种用来表现HTML标准通用标记语言的一个应用)或XML(标准通用标记语言的一个子集)等文件样式的计算机语言。CSS不仅可以静态地修饰网页,还可以配合各种脚本语言动态地对网页各元素进行格式化。[1] 
CSS 能够对网页中元素位置的排版进行像素级精确控制,支持几乎所有的字体字号样式,拥有对网页对象和模型样式编辑的能力。

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

今天在SegmentFault社区碰到了两个关于百分比计算的问题,一个是在translate中使用百分比的时候,是相对于哪个DOM元素的大小计算的;另外一个是在padding、margin等中使用百分比时,百分比又是怎么转为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

 style="width: 20px">      id="temp1" style="margin-top: 50%">Test top
id="temp2" style="margin-right: 25%">Test right id="temp3" style="margin-bottom: 75%">Test bottom id="temp4" style="margin-left: 100%">Test left

得到的offset如下:

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

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

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

Example 2: Positioned Elements

 style="height: 100px; width: 50px">      id="temp1" style="position: relative; top: 50%">Test top      id="temp2" style="position: relative; right: 25%">Test right      id="temp3" style="position: relative; bottom: 75%">Test bottom      id="temp4" style="position: relative; left: 100%">Test left 

得到的offset如下:

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

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

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

关键词:百分比计算方法,css支持的百分比计算方法





Copyright © 2012-2018 三度网教程(http://www.3du8.cn) .All Rights Reserved 网站地图 友情链接

免责声明:本站资源均来自互联网收集 如有侵犯到您利益的地方请及时联系管理删除,敬请见谅!

QQ:1006262270   邮箱:kfyvi376850063@126.com   手机版