注意:height一定是内容盒的高度,即在box-sizing:content-box的情况下,若为border-box时,此时的height为整个盒子的高度,需要减去padding,border、margin的尺寸才为真实的内容盒的height。
如一个盒子box-sizing:border-box,border:10px,height:40px,这时内容盒的高度应该为20px,line-height设置为20px就可实现上下居中。
注:box-sizing 属性的默认值是:content-box ,但实际开发中我们很多时候 可能为写成:box-sizing: content-box。
下面我们写一个box-sizing:border-box的例子:
<style>
div{
width: 200px;
height: 00px;
border: 20px solid red;
background-color: red;
height: 100px;
line-height: 100px;
box-sizing: border-box;
}
</style>
<div>好好学习</div>
很明显文字垂直不居中
当我们改为 box-sizing: content-box时;