垂直外边距的重叠
- 在网页中相邻的垂直方向的外边距,会发生外边距的重叠
-兄弟元素
兄弟元素之间的相邻外边距会取最大值而不是取和,谁大听谁的
特殊情况:如果相邻的外边距一正一负,则取两者的和
如果相邻的外边距都是负值,则取绝对值较大的
总结:兄弟元素的外边距重叠,对开发有利,不用处理
-父子元素
如果父子元素的垂直外边距相邻了,则子元素的外边距会传递给父元素
暂时解决方案:
1:不用外边距
2:使不相邻
3:开启元素的BFC隐含属性值
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<style type="text/css">
.box1 {
width: 100px;
height: 100px;
background-color: red;
/*
为上边的元素设置一个下外边距
*/
margin-bottom: -120px;
/* margin-top: 100px; */
}
.box2 {
width: 100px;
height: 100px;
background-color: green;
margin-top: -100px;
/**
为下边的元素设置一个上外边距
*/
/* margin-top: -100px; */
}
.outer {
width: 200px;
height: 200px;
background-color: yellow;
/* 方案1:用padding ,改父元素高度*/
padding-top: 100px;
height: 100px;
/*方案2:为outer设置一个上边框 会改变盒子的大小,有个1px的边框*/
/* border-top: 1px transparent solid; */
}
.inner {
width: 100px;
height: 100px;
background-color: yellowgreen;
/*为子元素设置一个上外边距,使子元素的位置下移 */
/* margin-top: 100px; */
}
</style>
</head>
<body>
<!-- 兄弟元素 -->
<!-- <div class="box1"></div>
<div class="box2"></div> -->
<!-- 父子元素 -->
<div class="outer">
<div class="inner"></div>
</div>
</body>
</html>