margin-top失效常见症状及解决方法

开发 前端
CSS中margin-top属性非常实用,但是有时可能会失效,这里和大家分享一下margin-top失效的解决方法,相信本文介绍对你的学习一定会有所帮助。

本文向大家描述一下margin-top失效的解决方法,margin-top失效常出现两种情况来介绍,这里来和大家分享一下,希望本文的介绍一定会让你有所收获。

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

常出现两种情况:

(一)margin-top失效

先看下面代码:

  1. <div> 
  2. <divclassdivclass="box1">float:left</div> 
  3. <divclassdivclass="box2">clear:both;margin-top:20px;</div> 
  4. </div> 
  5.  

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

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

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

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

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

◆解决办法:

1.box2增加float属性

2.box1与box2之间增加一层"<divstyle="clear:both;"></div>"

(二)子元素设置margin-top作用于父容器

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

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

◆解决办法:

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

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

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

【编辑推荐】

  1. Firefox下margin-top失效解决技巧
  2. 十大CSS使用经典技巧
  3. CSS属性font-size用法详解
  4. 探究采用DIV+CSS框架的利与弊
  5. DIV CSS网页布局需要掌握的八大技巧

 

 

责任编辑:佚名 来源: hi.baidu.com
相关推荐

2010-08-31 09:19:46

margin-topFirefox

2010-08-26 13:54:33

Firefoxmargin-top

2010-09-08 09:28:33

CSSmargin-top

2010-09-13 17:15:59

margin-top

2010-08-31 09:06:25

Firefox margin-top

2010-08-25 10:46:53

margin-topCSS

2010-08-25 10:05:03

margin-top

2010-08-30 16:53:14

FirefoxIE8margin-top

2010-08-25 09:48:25

CSSmargin

2011-04-29 13:22:48

ThinkPad笔记本故障

2011-05-06 17:25:58

硒鼓

2009-08-24 10:37:11

Silverlight

2010-08-10 10:10:34

Flex内存泄露

2022-04-06 10:09:17

云服务云计算

2018-11-01 15:26:38

开源软件安全

2010-08-31 13:49:12

CSS

2011-06-16 10:27:55

.NET内存泄漏

2009-03-04 10:38:36

Troubleshoo桌面虚拟化Xendesktop

2018-05-29 11:44:22

数据库MySQL死锁

2012-11-19 11:30:40

PowerShell常见问题解决方法
点赞
收藏

51CTO技术栈公众号