穿透
4.2 解决Margin穿透1-BFC
可以使用overflow:hidden,触发BFC模型解决这个问题,有专门章节介绍BFC模型。
4.3 解决Margin穿透2-插入元素
在父元素中,插入一个高度、宽度都是0px的隐藏元素.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Margin穿透问题</title>
<style type="text/css">
body{
margin: 0px;
}
.header{
height: 100px;
background: red;
}
.logo{
background: blue;
width: 60px;
height: 60px;
margin-top: 40px;
}
.before{
width: 0px;
height: 0px;
overflow: hidden;
visibility: hidden;
}
</style>
</head>
<body>
<div class="header">
<div class="before"></div>
<div class="logo"></div>
</div>
</body>
</html>
4.4 解决Margin穿透3-:before
与插入元素的思路一致,使用伪元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Margin穿透问题</title>
<style type="text/css">
body{
margin: 0px;
}
.header{
height: 100px;
background: red;
}
.logo{
background: blue;
width: 60px;
height: 60px;
margin-top: 40px;
}
.header:before{
width: 0px;
height: 0px;
display: block;
content: 'clear';
overflow: hidden;
visibility: hidden;
}
</style>
</head>
<body>
<div class="header">
<div class="logo"></div>
</div>
</body>
</html>
5、空元素合并
源代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>空元素合并</title>
<style type="text/css">
.div1{
width: 100px;
height: 100px;
background: blue;
}
.div2{
margin-top: 50px;
margin-bottom: 100px;
}
.div3{
width: 100px;
height: 100px;
background: red;
}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
</body>
</html>
运行结果: div2 理论占据150px=上边距+下边距,实际占用了100px。因为空元素上下边距合并。如果div2的内容添加文字,显示效果将会有巨大差异。