概述
最内部的 content 是元素实际内容,它的外侧是内边距 padding,内边距外侧是边框 border,边框外侧是外边距 margin,margin 是透明的,不会遮挡被当前元素覆盖的元素
盒子类型
标准盒模型
标准盒模型的内容区域就是 content 所占区域
它的宽 width 即为 content 的宽,高 height 即为 content 的高
- 在标准盒模型下,修改内边距 padding 和边框 border 会撑大盒子,要注意元素之间的位置
- 设置标准盒模型:
box-sizing: content-box;
默认值,不用特别去修改
IE 盒模型
IE 盒模型的内容区域是 内容 content + 内边距 padding + 边框 border
它的宽是三者的宽相加,它的高是三者的高相加
- 在 IE 盒模型中,修改内边距 padding 和边框 border 会向内扩展,故也称内减模式
- 设置 IE 盒模型:
box-sizing: border-box;
两个 BUG
测试代码在最后
1. margin 塌陷
子元素的 margin-top 不相对父元素上边线定位,而是相对于父级元素的父级元素定位
若子级元素的 margin-top 超过父级,则会带动父级元素一起移动
2. margin 合并
垂直方向上的两个元素,margin-top 与 margin-bottom 会合并
解决方法
- 加边框 border
- 形成 BFC — Block Format Context — 块级格式化上下文
/* 下面是四种方法 */
/* 绝对定位 */
position: absolute;
/* 赋予 inline 属性 */
display: inline-box;
/* 使盒子浮动 */
float: left;
/* 设置 overflow */
overflow: hidden;
测试代码
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BOX MODEL</title>
<style>
.wrapper {
border-top: 2px solid black;
}
.father {
margin-left: 100px;
margin-top: 50px;
margin-bottom: 100px;
width: 200px;
height: 200px;
background-color: #f88;
}
.son {
margin-top: 100px;
width: 100px;
height: 100px;
background-color: #088;
}
.mother {
margin-left: 100px;
margin-top: 100px;
width: 200px;
height: 200px;
background-color: #008;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="father">
<div class="son"></div>
</div>
<div class="mother">
</div>
</div>
</body>