CSS中的百分比(%)如何使用???

时间:2023-03-10 07:13:29
CSS中的百分比(%)如何使用???

除了height以外垂直方向上的margin-top(bottom)或者padding-top(bottom)的百分比取值都是相对于父元素的宽度

默认的content-box盒模型下元素的width就是指的content的宽度

.box {
width: 200px;
height: 400px;
padding: 50px;
border: 1px solid #000;
}
.child {
width: 100px;
height: 50%;
padding-bottom: 50%;
border: 1px solid #000;
}
当然这是border-box盒模型,width的百分比计算:
height = 父height*50% = (400px*50%) = 200px
padding-bottom = (父width200px - 父padding50px*2) *50%= 50px
因为这个是border-box盒模型,所以计算时要加上padding宽度的;
如果我们的盒子模型是content-box盒模型,就如下计算公式:
padding-bottom = (父width200px)*50% = 100px