CSS盒模型学习

盒模型(box model)是CSS中的一个重要概念,它是元素大小的呈现方式。需要记住的是:”every element in web design is a rectangular box”任何元素在web设计中都是一个方形的盒子。

可以认为每个html标签都是一个方块,然后这个方块又包着几个小方块,如同盒子一层层的包裹着,这就是所谓的盒模型。

盒模型类型

  1. W3C 标准盒模型(content-box):属性width,height只包含内容content,不包含border和padding。

  2. IE 盒模型(border-box):属性width,height包含border和padding,指的是content+padding+border。

    在ie8+浏览器中使用哪个盒模型可以由box-sizing(CSS新增的属性)控制,默认值为content-box,即标准盒模型;如果将box-sizing设为border-box则用的是IE盒模型。如果在ie6,7,8中DOCTYPE缺失会触发IE模式。在当前W3C标准中盒模型是可以通过box-sizing自由的进行切换的。

盒模型大小

content-box(默认)

布局所占宽度Width:
Width = width + padding-left + padding-right + border-left + border-right

布局所占高度Height:
Height = height + padding-top + padding-bottom + border-top + border-bottom

border-box

布局所占宽度Width:
Width = width(包含padding-left + padding-right + border-left + border-right)

布局所占高度Height:
Height = height(包含padding-top + padding-bottom + border-top + border-bottom)

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE HTML>
<html>
<body>
<style type="text/css">
div {
width:200px;
height:200px;
padding:10px;
border:10px solid black;
background-color:red;
color: white;
font-size: 20px;
}
.div1 {
box-sizing: content-box
}
.div2 {
box-sizing: border-box
}
</style>
<div class="div1">
content-box
</div>
<div class="div2">
border-box
</div>
</body>
</html>

总结

border-box下盒子的大小即为指定的大小,其对内内容区域受到border和padding的压缩,内容区域即小于等于盒子宽高。

content-box下盒子的宽高等于content的宽高+padding+border的大小,样式中指定的大小为content的大小。