1、在上下盒子的布局中,盒子的垂直间隙是最大的那个margin值,即会有重叠问题。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box1 {
height: 200px;
width: 200px;
background-color: #51b7ec;
margin-bottom: 30px;
}
.box2 {
height: 200px;
width: 200px;
background-color: purple;
margin-top: 20px;
}
</style>
</head>
<body>
<!--在上下盒子的布局中,盒子的垂直间隙是最大的一个值-->
<div class="box1">
</div>
<div class="box2">
</div>
</body>
</html>
结果展示:
解决方式:只给上盒子设置margin-bottom,或者只给下盒子设置margin-top。
2、外边距的重叠只会发生在垂直方向,但是即使设置了margin:0;也依然会有空白间隙的问题。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
height: 200px;
width: 200px;
background-color: #51b7ec;
display: inline-block;
/*margin-right: 30px;*/
}
.box2 {
height: 200px;
width: 200px;
background-color: purple;
display: inline-block;
/*margin-left: 20px;*/
}
</style>
</head>
<body>
<div class="box1">
<!--外边距的重叠只会发生在垂直方向-->
</div>
<div class="box2">
</div>
</body>
</html>
结果展示:
解决空白间隙的问题:
展示结果:
3、父子盒子情况下,如果子盒子设置了margin-top,会导致父子盒子都向下偏移。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.outer {
width: 200px;
height: 200px;
background-color: purple;
}
.inner {
width: 100px;
height: 100px;
background-color: red;
margin-top: 100px;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner"></div>
</div>
</body>
</html>
结果:
解决方案:
1、给父盒子设置border.
.outer {
width: 200px;
height: 200px;
background-color: purple;
border-top: 1px solid transparent;/*transparent:透明的*/
}
2、给父盒子设置overflow: hidden;
.outer {
width: 200px;
height: 200px;
background-color: purple;
overflow: hidden;
}
3、给父盒子设置padding-top,并减去height相应的高度,子盒子去掉margin-top。
.outer {
width: 200px;
height: 100px;
background-color: purple;
padding-top: 100px;
}
.inner {
width: 100px;
height: 100px;
background-color: red;
}
结果: