在css属性中,很多属性的取值可以是百分比,比如:width、height、padding、margin、font-size、line-height、background-position等,那么这些百分比值的计算是相对于谁呢?
先来看几个例子,分别是正常文档流中、浮动情况下和定位情况下。
正常文档流中:
<div class="parent">
<div class="child">
css百分比在正常文档流的体现
</div>
</div>
.parent {
width: 500px;
height: 300px;
padding:50px;
background: #999;
margin-left:50px;
font-size: 15px;
line-height:30px;
border: 1px solid #808080;
}
.child {
width: 50%;
height: 20%;
padding-left: 10%;
margin-left:10%;
border:2px solid black;
font-size: 150%;
line-height: 150%;
background: orange;
}
此时,class为parent的div元素的content-box的宽度、高度值分别为500px、300px;padding-box的宽度、高度分别为600px、400px,如下图所示:
当为child元素设置float为left后,结果与上述一样,即浮动下各属性百分比的计算是和正常文档流中一样的。
当为元素设置定位后,
.parent {
width: 500px;
height: 300px;
padding:50px;
background: #999;
margin-left:50px;
font-size: 15px;
line-height:30px;
border: 1px solid #808080;
position: relative;
}
.child {
width: 50%;
height: 20%;
padding-left: 10%;
margin-left:10%;
border:2px solid black;
font-size: 150%;
line-height: 150%;
background: orange;
position:absolute;
top:20%;
left:20%;
}
子元素的宽度、高度、内外边距等属性值变化如下所示:
由上述三个例子,总结如下:
一、font-size
当前的字体大小等于100%
二、line-height
line-height的计算值就是当前字体的值乘以该百分比。注意line-height取值为数值或者百分比的差异,此处不细致讲解。
三、width
正常文档流中和设置浮动的情况下,相对于父元素content-box的宽度;绝对定位时,相对于包含块padding-box的宽度。
四、height
height对百分比也是支持的,但是其和width还是有一个明显的区别:当父元素width属性为auto时,子元素宽度仍然可以使用百分比设置。但是对于height,只要子元素还是在正常文档流当中的,如果父元素的height属性为auto,则子元素height设置为百分比会被忽略。规范中指出:如果包含块的高度没有显式指出(即高度由内容决定),并且该元素不是绝对定位,则计算值为auto。而auto*100/100=NaN。所以,若要高度的百分比设置有效,需要如下设置:
html,body{
height:100%
}
上述高度计算,都是对于正常流
五、margin、padding
无论是垂直或水平方向,均是相对于父元素的宽度,正常文档流中和设置浮动的情况下,相对于父元素content-box的宽度;绝对定位时,相对于包含块padding-box的宽度。
六、background-position
具体见我的另一篇文章,有细致讲解《CSS之background》。
七、定位元素的left/right/bottom/top百分比值
top,bottom设置百分比定位是按包含块padding-box的高度来计算的,同样left,right,设置百分比定位是按包含块padding-box的宽度来计算的。