边距重叠问题

转自http://www.lingdublog.com/51.htmlhttp://www.zhangxinxu.com/study/200908/margin-overlap.html
css的盒子模型里是这样规定两个对象之间的距离的:对象之间的间距是由两个对象的盒子模型的最终计算值得出来的,也就是说两个对象之间的间距就是两个对象的距离,但是当遇到两个对象一个有下外边距margin,一个有下外边距margin,这个问题变得有点复杂。我们来看看。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<title>Margin上下边距重叠问题</title>  
<style>  
#one{width:200px;height:100px;background-color:#ff0000;margin:10px;}  
#two{width:200px;height:100px;background-color:#00ff00;margin:10px;}  
</style>  
</head>  
<body>  
<div id="one"></div>  
<div id="two"></div>  
</body>  
</html>  

这里写图片描述
如果你认为one和two盒子的距离是20px,那你就错了,它们的真正距离是10px。
这是css的一个特性,当空白边叠加时,以较大的margin值为准。这在html和xhtml中都是一样的情况。
但如果把上例中的one和two盒子都进行float,那情况又不同了,如:

<style>  
#one{width:200px;height:100px;background-color:#ff0000;margin:10px;float:left;}  
#two{width:200px;height:100px;background-color:#00ff00;margin:10px;float:left;clear:both;}  
</style> 

若只针对一个div设置了浮动,则效果如图:
这里写图片描述

这时one与two盒子之间的上下距离变成了20px,这就是说当两个对象都浮动的情况下就不再遵守空白边叠加的规则了。这里写图片描述

同向重叠:上边距与上边距重叠
异向重叠: 下边距与上边距重叠
这里写图片描述

同时解决同向边距重叠和异向边距重叠

给包含块设置float:left或者overflow:hidden;再给子元素设置float:left
原理:设置浮动之后,元素自动以display:inline-block的方式显示

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<title>Margin上下边距重叠问题</title>  
<style>  
*{
    margin: 0;
    padding: 0;
}
#wrap{background-color:#999;margin:20px; float: left;}
#one{height:100px;background-color:#ff0000;margin:20px; float: left;}  
#two{height:100px;background-color:#00ff00;margin:20px;float: left;clear: both;}  
</style>  
</head>  
<body>  
<div id="wrap">
<div id="one">111</div>  
<div id="two">222</div>  
</div>
</body>  
</html> 

这里写图片描述

解决同向边距重叠问题

方法一:给包含块设置overflow:hidden;
方法二、给包含块设置一些边缘属性,如padding、border

#wrap{background-color:#999;margin:20px; padding: 1px;}
#one{height:100px;background-color:#ff0000;margin:20px; }  
#two{height:100px;background-color:#00ff00;margin:20px; }  

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值