1.CSS 盒模型(Box Model)
把所有 HTML 元素都看作是一个 盒子(Box),这个盒子包着一层又一层, 这就是盒模型。
随便写个 div, 打开 Chrome 的开发者工具, 在右边栏能看到这样一个直观的盒模型图.
<div class="container">
<div class="box">盒模型</div>
</div>
.container {
display: flex;
align-items: center;
justify-content: center;
width: 300px;
height: 300px;
background-color: #e6ebf1;
}
.box {
width: 100px;
height: 100px;
margin: 10px;
border: 1px solid orange;
padding: 5px;
color: #555;
font-size: 20px;
text-align: center;
line-height: 100px;
}
这个 div 从外到内被分成了四层, 分别是:
- Margin(外边距) - 清除边框外的区域, 外边距是透明的
- Border(边框) - 围绕在内边距和内容外的边框
- Padding(内边距) - 清除内容周围的区域, 内边距是透明的
- Content(内容) - 盒子的内容, 显示文本和图像等
2.box-sizing
盒模型又被分为 IE盒模型 和 W3C标准盒模型 两种类型。
在 IE8+ 的浏览器中要使用哪个盒模型可以由 box-sizing 控制。
默认值为 content-box, 即W3C标准盒模型;
如果将 box-sizing 设为 border-box 则用的是IE盒模型。
这两者的区别在于:
- IE盒模型( box-sizing: border-box )的盒子大小为 content + padding + border。
.box { width: 100px; height: 100px; margin: 10px; border: 1px solid orange; padding: 5px; color: #555; font-size: 20px; text-align: center; line-height: 100px; box-sizing: border-box; // 添加box-sizing }
上图中可以看到元素(盒子)的总大小为 (200 * 200)px。content 则是被压缩成了 ((100 - (5 + 1) * 2) = 88)px。 - W3C标准盒模型( box-sizing:content-box )的盒子大小为 content, 不包括 padding 和 border,后两者另算大小。上图可以看到元素(盒子)的总大小为 (132 * 132)px, 这个 132 就是 100 + (10 + 1 + 5) * 2 得出来的。
content 大小为 200,padding 和 border 另算大小。总和大小就是元素(盒子)的总大小。