在网页布局中,有时需要设置css设置外边距(margin), 但是会出现css外边距合并(即重叠)的情况。什么是外边距合并的情况呐?怎么解决呐?
1.外边距的合并
css外边距合并(重叠)是指两个相邻的块级元素(兄弟元素),当上下两个边距相遇时,外边距会产生重叠的现象,且重叠后的外边距等于其中较大者。
示例:
<style type="text/css">
#container div{
width: 200px;
height: 200px;
}
#d1{
background-color: #f00;
margin-bottom: 40px;
}
#d2{
background-color:#7FFFD4;
margin-top: 30px;
}
</style>
</head>
<body>
<div id="container">
<div id="d1"></div>
<div id="d2"></div>
</div>
</body>
效果:
本来两个元素之间应该是70px的间距。现在合并成40px,以大的为准。
2.解决方案:
在设计的时候规避
(1).单独写一个上外边距或者下外边距
(2).给下面的盒子设置定位(position: absolute;)
(3).给下面的盒子设置浮动(float: left;)
(4).给任意一个设置成行内块元素(display: inline-block;)
方法1效果:
<style type="text/css">
#container div{
width: 200px;
height: 200px;
}
#d1{
background-color: #f00;
margin-bottom: 70px;
}
#d2{
background-color:#7FFFD4;
}
</style>
方法2效果:
<style type="text/css">
#container div{
width: 200px;
height: 200px;
}
#d1{
background-color: #f00;
margin-bottom: 40px;
}
#d2{
background-color:#7FFFD4;
margin-top: 30px;
position: absolute;
}
</style>
方法3效果:
<style type="text/css">
#container div{
width: 200px;
height: 200px;
}
#d1{
background-color: #f00;
margin-bottom: 40px;
}
#d2{
background-color:#7FFFD4;
margin-top: 30px;
float: left;
}
</style>
方法4效果:
<style type="text/css">
#container div{
width: 200px;
height: 200px;
}
#d1{
background-color: #f00;
margin-bottom: 40px;
display: inline-block;
}
#d2{
background-color:#7FFFD4;
margin-top: 30px;
}
</style>