教程集 www.jiaochengji.com
教程集 >  CSS教程  >  经典实例  >  正文 CSS中的百分比的使用方法

CSS中的百分比的使用方法

发布时间:2020-05-07   编辑:jiaochengji.com
教程集为您提供CSS中的百分比的使用方法等资源,欢迎您收藏本站,我们将为您提供最新的CSS中的百分比的使用方法资源
百分比在web开发应用中我们会用到很多,但通常只用于宽度的百分比了,下文我们要介绍的百分比用法估计超出你的想象


CSS支持多种单位形式,如百分比、px、pt、rem等,百分比和px是常用的单位,随着移动端和响应式的流行,rem、vh、vw也开始普遍使用,这些单位你可能未必知道,想了解?可以戳此文:CSS:7个你可能不认识的单位。

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

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

[The percentage] refer[s] to the size of the element’s box
具体参考:css3 translate in percent (自备梯子)

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

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

得到的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
<div style="height: 100px; width: 50px">
<div id="temp1" style="position: relative; top: 50%">Test top</div>
<div id="temp2" style="position: relative; right: 25%">Test right</div>
<div id="temp3" style="position: relative; bottom: 75%">Test bottom</div>
<div id="temp4" style="position: relative; left: 100%">Test left</div>
</div>

得到的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
虽然有点困惑,但只需要记住:对于margin和padding,百分比按照父元素的宽计算,对于定位元素,则按照父元素的高计算。

您可能感兴趣的文章:
CSS中的百分比的使用方法
详细学习CSS中的网页布局的属性
CSS手册简编:文本属性
百度浏览器积分兑换爱奇艺会员的方法
百度云盘不能上传超过4G大小的文件如何解决?
百度云资源分享群组怎么使用?
一定要学CSS吗?有什么理由?
Div CSS网站设计的优点
分析各浏览器对css百分比小数点反应
css line-height 控制行高

[关闭]
~ ~