小菜学习日记—div嵌套导致子区域margin-top失效问题(外边距合并问题)

来源:互联网 发布:mac dare you和diva 编辑:程序博客网 时间:2024/06/05 10:40

小菜学习日记—div嵌套导致子区域margin-top失效问题(外边距合并问题)

CSS布局中margin-top属性失效的解决方法,常见的有两种情况,一种是普通的margin-top失效,另一种就是子元素设置margin-top作用于父容器。

关于margin-top属性失效的解决方法

常出现两种情况:

(一)margin-top失效

先看下面代码:

<div> <divclassdivclass="box1">float:left</div> <divclassdivclass="box2">clear:both;margin-top:20px;</div> </div> 

两个层box1和box2,box1具有浮动属性,box2没有,这时候设置box2的上边距margin-top没有效果。


网上能找到的两种比较靠谱的解释:

1:“在CSS2.1中,水平的margin不会被折叠;垂直margin可能在一些盒模型中被折叠…”


2:当第一个层浮动,而第二个没浮动层的margin会被压缩,详见–浮动元素后非浮动元素的margin的处理。


得到解决问题思路:要浮动一起浮动,要就一起不浮动。


解决办法:


1.box2增加float属性


2.box1与box2之间增加一层”

<divclassdivclass="box"style="height:100px;background:red;"> <divclassdivclass="box2">clear:both;  margin-top:20px;height:50px;width:500px;  background:#000;</div> </div> 

当给box2设置margin-top时,在FF下仅作用于父容器。


解决办法:


1.给父容器box加overflow:hidden;属性


2.父容器box加border除none以外的属性


3.用父容器box的padding-top代替margin-top

0 0
原创粉丝点击