今天介绍一下前端中的一个基本概念:盒模型。
1、盒模型分类
CSS盒模型本质是一个盒子,由边距、边框、填充和实际内容组成。 CSS盒模型分为两种:标准盒模型、IE盒模型(也称为怪异盒模型)。 两种盒模型的区别在于他们的总宽度的计算公式不一样。 在文档首部加了 声明,即使用标准盒模型,若不加,则会由浏览器自己决定。
CSS 中的 box-sizing 属性定义了 user agent(用户计算机程序)应该如何计算一个元素的总宽度和总高度。box-sizing的属性值有以下两种:border-box(IE盒模型)、content-box(标准盒模型)。
标准盒模型
标准盒模型如下图:
width = content => 改变padding或border之后div所占用区域就会外扩,而具体内容所在的区域不会变化
标准盒模型的示例代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.content-box{
width: 80px;
height: 80px;
padding: 5px;
border: 5px solid black;
box-sizing: content-box;
}
</style>
</head>
<body>
<div class="content-box"></div>
</body>
</html>
IE盒模型
IE盒模型如下图:
width = content + padding + border => 改变padding或者border之后div所占区域不外扩,而具体内容所在的区域的会缩小
IE盒模型的示例代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.border-box{
width: 100px;
height: 100px;
padding: 5px;
border: 5px solid black;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="border-box"></div>
</body>
</html>
注意:在浏览器调试的时候可通过改变相应div的宽度和高度查看页面变化情况。
2、外边距折叠问题
常规块盒子有一种机制叫外边距折叠,即垂直方向上的两个外边距相遇时,会折叠成一个外边距,且折叠之后的外边距高度为两者之中较大的那一个。现在给类名为"top"、"bottom"两个盒子都设置宽度、高度且都为"100px"、都设置外边距且都为"10px",可以添加任意颜色便于区分两个盒子。此时通过调试工具可以发现两个盒子之间的距离为"10px",并不是"20px",说明已经发生了外边距折叠。 外边距折叠好像很奇怪,实际上却很有用。当一个页面包含了多个段落,如果没有外边距折叠,从第二个段落开始,所有段落的间距都是最上方段落的上外边距的两倍,有了外边距折叠,段落间距才会相等。 如果想要清除两个盒子之间的外边距折叠,可以给目标盒子设置以下属性:
- display: inline-block
- float属性值不是"none"的元素
- 绝对定位
下面的代码通过绝对定位实现了两个盒子之间的外边距折叠问题的解决:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.top {
width: 100px;
height: 100px;
margin: 10px;
background-color: red;
}
.bottom {
width: 100px;
height: 100px;
margin: 10px;
background-color: green;
position: absolute;
}
</style>
</head>
<body>
<section class="top"></section>
<section class="bottom"></section>
</body>
</html>