Skip to content

box-sizing 涉及到盒子模型

css 中的元素默认是以 content-box 形式来渲染的。

即设置的widthcontent-width,元素的真实宽度为 border + padding + content-width

如下例,虽然设置的 width: 250px;height: 250px;,但元素的真实宽高会是 450px

html
<style>
  .box {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 250px;
    height: 250px;
    margin: 50px;
    padding: 50px;
    border: 50px solid #000;
    background: skyblue;
  }
  .content {
    width: 50px;
    height: 50px;
    background: #fff;
  }
</style>

<div class="box">
  <div class="content"></div>
</div>

这对于日常开发来说,是不太友好的。总不能在切图的时候还要手动计算。

而在 CSS3 中提供了 box-sizing: border-box; 的设置方式。

顾明思义,border-box 会将元素的 bodrer 范围以内作为整体元素来渲染,即 width = border + paddding + content-width

同样,按照上例设置的 width: 250px;height: 250px;,但在 border-box 的条件下元素的真实宽高会是 250px

html
<style>
  .border-box {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 250px;
    height: 250px;
    margin: 50px;
    padding: 50px;
    border: 50px solid #000;
    background: skyblue;
    box-sizing: border-box;
  }
  .border-content {
    width: 50px;
    height: 50px;
    background: #fff;
  }
</style>

<div class="box">
  <div class="content"></div>
</div>