百分比是一种相对于包含块的计量单位。
首先知道百分比的宽度:
目标元素宽度/父级元素宽度=百分比宽度
在说到百分比是前,先简单了解下基本的单位
- 英寸(inch) :in 1 in=2.54cm
- 厘米(centimeter):cm
- 毫米(millimeter):mm
- 磅(point):pt 1pt=1/72 in
- 皮卡(pica):pc 1pc==12 pt
- 像素(pixel unit):px 1px=0.75 pt
- 相对长度单位(相对于当前对象内文本的字体尺寸):em 1em=16px
CSS3新增的一个相对单位root em: rem 1rem=16px
接下来就是关于CSS中常用属性的百分比
width 基于父级的width height 基于父级的height margin(top,right,bottom,left) 基于父级的width padding(top,right,bottom,left) 基于父级的width left,top,right,bottom 基于父元素的width,height,width,height font-size 基于继承得到的font-size line-height 基于当前字体的font-size transform(left, top) 基于自身的left, top
百分比的demo
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.box{
position: relative;
margin-top: 10%;
width: 100px;
height: 100px;
padding: 15px;
border: 4px solid yellow;
background: red;
}
.box>.absolute-div{
z-index: 1;
position: absolute;
top: 100%;
left: 100%;
width: 10%;
height: 10%;
padding: 10%;
border: 4px solid blue;
background: white;
}
.box>.relative-div{
z-index: 1;
position: relative;
top: 100%;
left: 100%;
width: 10%;
height: 10%;
padding: 10%;
border: 4px solid blue;
background: white;
}
</style>
<div class="box">
<div class="relative-div"></div>
</div>
<div class="box">
<div class="absolute-div"></div>
</div>
父盒子盒模型与相对定位的子盒子的盒模型(relative):
父盒子盒模型与相对定位的子盒子的盒模型(absolute):