外边距合并问题是面试中考官常问的问题之一,也是前端必须要掌握的一部分知识,下边就让我来带大家认识一下吧!
一·父子之间外边距合并
当父元素或子元素与浏览器边框或其他的元素拥有一定外边距的时候,一般呈现外边距较大的一方的效果,例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0px;
padding: 0px;
}
#div1{
width: 200px;
height: 200px;
background: #ff0000;
margin-top: 200px;
}
#div2{
width: 100px;
height: 100px;
background: #00b262;
margin-top: 100px;
/*float: left;*/
/*position: absolute;*/
}
</style>
</head>
<body>
<div id="div1">
<div id="div2">
</div>
</div>
</body>
</html>
div1y与div2两者的外边距都为200px,而如果div2想要相对于div1拥有外边距100px则无法实现,这种情况有以下几种解决办法:
1在父元素上边加上
overflow: hidden;
2在父元素或子元素上边加上浮动或定位
float: left;
或
position: absolute;
3在父元素上加上边框
border: 1px solid red;
结果代码如下:
二兄弟元素外边距合并
兄弟之间在相邻的方向上都有外边距,结果会显示为较大的一方的效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0px;
padding: 0px;
}
#div1{
width: 200px;
height: 200px;
background: red;
margin-bottom: 200px;
}
#div3{
width: 200px;
height: 200px;
background: #00b262;
margin-top: 100px;
position: absolute;
}
</style>
</head>
<body>
<div id="div1">
</div>
<div id="div3">
</div>
</body>
</html>
解决办法同父子之间的一样。