# CSS 盒子模型

所有HTML元素可以看作盒子,在CSS中,"box model"这一术语是用来设计和布局时使用。

CSS盒模型本质上是一个盒子,封装周围的HTML元素,它包括:边距,边框,填充,和实际内容。

盒模型允许我们在其它元素和周围元素边框之间的空间放置元素。

下面的图片说明了盒子模型(Box Model):

  • margin(外边距) - 清除边框外的区域,外边距是透明的。
  • border(边框) - 围绕在内边距和内容外的边框。
  • padding(内边距) - 清除内容周围的区域,内边距是透明的。
  • content(内容) - 盒子的内容,显示文本或图像。

# 标准盒子模型(W3C 标准盒模型)

W3C标准盒子模型中width指的是内容区域content的宽度,height指的是内容区域区域content的高度。

width = 内容区域的宽度

height = 内容区域的高度

W3C标准盒子模型的总宽 = width + 左右内边距(padding) + 左右边框(border) + 左右外边距(margin)

W3C标准盒子模型的总高 = height + 上下内边距(padding) + 上下边框(border) + 上下外边距(margin)

设置标签成W3C 标准盒模型的css属性 如下:

box-sizing: content-box;

# IE 盒子模型(怪异盒模型)

ie怪异盒子模型中的width指的是内容、边框、内边距总的宽度(content + border + padding);height指的是内容、边框、内边距总的高度

width = 内容区域的宽度 + 边框 + 内边距

height = 内容区域的高度 + 边框 + 内边距

ie怪异盒子模型的总宽 = width + 左右外边距(margin)

ie怪异盒子模型的总高 = height + 上下外边距(margin)

设置标签成ie怪异盒子模型的css属性 如下:

box-sizing: border-box;
 <div class="box"></div>
 <div class="con"></div>
.box {
    position: relative;
    padding: 10px;
    width: 100px;
    height: 100px;
    background-color: #ccc;
    border: 1px solid black;
    box-sizing: border-box;
    margin: 20px;
    display: inline-block;
    vertical-align: top;
}

.con {
    display: inline-block;
    vertical-align: top;
    box-sizing: content-box;
    width: 100px;
    height: 100px;
    background-color: red;
    border: 1px solid gray;
    padding: 10px;
    margin: 20px;
}
更新时间: 2021年8月30日星期一晚上10点43分