<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
hr {
margin: 0;
}
body {
margin: 0;
padding: 0;
}
.box1 {
width: 100px;
height: 100px;
background-color: #bfa;
margin-bottom: 50px;
}
.box2 {
width: 100px;
height: 100px;
background-color: rgb(255, 170, 237);
margin-top: 150px;
}
.parent {
width: 200px;
/* height: 200px; */ /*当不设置父元素的高度,它的高度由子元素决定;
当设定了父元素的高度(无论设置多少,只要设置了就行),
那父元素的下外边距不会和内部子元素的下外边距折叠 */
background-color: #bfa;
margin-bottom: 50px;
}
.son {
width: 100px;
height: 100px;
background-color: rgb(255, 170, 237);
margin-top: 50px;
margin-bottom: 200px;
}
.son2 {
/* 从演示中, 也可以看出:
有没有son2这个div(在parent没有设置高度的情况下,即auto)
会决定son1给的margin-bttom是否能 撑起parent元素的的高度
(补充:想想, 这也是正常现象, parent元素,默认高度auto,这本来就是由子元素的高度撑开的,
假设没有son2这个元素,但是给parent添加一个border-bottom,
那么margin-bottom仍然能继续撑开parent元素的高度)
*/
/*
那其实根据这个, 也可以推出来一种情况:
一个parent类的div元素, 假设设定一个padding:5px(为了防止父子元素边距折叠),
内部嵌入一个div, 这个div设置margin-top, 就可以撑开parent元素的高度(前提是parent元素的高度是auto)
那这个不就有点像清除浮动的原理么?
*/
width: 100px;
height: 100px;
background-color: magenta;
}
.tail {
width: 100px;
height: 100px;
background-color: #000;
}
</style>
</head>
<body>
<div class="box1">box1</div>
<div class="box2">box2</div>
<hr/>
<div class="parent">
<div class="son">son</div>
<div class="son2">son2</div>
</div>
<div class="tail"></div>
</body>
</html>