magin、padding设置百分比问题
小示例镇楼
先给出一个很简单的demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style type="text/css">
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
}
.top {
width: 100%;
height: 10%;
padding-top: 5%;
background-color: red;
}
.bottom {
width: 100%;
height: 85%;
background-color: black;
}
</style>
</head>
<body>
<div class="top">
</div>
<div class="bottom">
</div>
</body>
</html>
问:上面的示例得到的高度正好是屏幕的百分百吗?如果你觉得这是一个low的问题并知道答案,就不用再看啦。
背景描述
我们项目中做了一个类似的事情,给加了一个.top的div加了一个padding-top值,看上面示例,自以为的高度总和:height(top) + padding-top(top) + height(bottom) = 10% + 5% + 85% = 100%正好撑满整个屏幕高度呢,但是实际并不然,高度已经超出了屏幕并产生了滚动条,如下图:
margin、padding百分比
真是原因很简单,margin、padding四个方向的百分比设置均是以父级元素的宽度决定的,即和高度没有什么关系,所以假如父级元素的width为200px、height为100px,那么如果设置子级元素的margin-top|bottom|left|right、padding-top|bottom|left|right为10%,各个值就都是20px。
当然,这是在默认的情况 writing-mode: horizontal-tb; 和 direction: ltr; 的情况下,当书写模式变成纵向的时候,其百分比将会变成父级元素块的height决定。
为什么要选择宽度做参照而不是高度呢?
这其实更多的要从CSS设计意图上去想,因为CSS的基础需求是排版,而通常我们所见的横排文字,其水平宽度一定(仔细回想一下,如果没有显式的定义宽度 或者强制一行显示,都会遇到边界换行,而不是水平延展),垂直方向可以无限延展。但当书写模式为纵向时,其参照就变成了高度而不再是宽度了。