margin-top问题:在chrome中2个div,一个嵌套另一个,被嵌套的那个层的margin-top不起作用,div2在Chrome浏览器中总是0px顶着div1

问题:在chrome中2个div,一个嵌套另一个,被嵌套的那个层的margin-top不起作用,div2在Chrome浏览器中总是0px顶着div1

代码:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>

<style type="text/css">

<!--

    body{

   background-color:#AEB9F4;

}

#div1{

  width:602px;

  height:602px;

  margin:20px auto;

  background-color:#EDD923;

}

#div1 #div2{

  margin-top:20px;

  margin-right:20px;

  margin-bottom:20px;

  margin-left:20px;

  width:560px;

  height:560px;

  border:1px solid #000;

}

-->

</style>   

</head>

<body>

   <div id="div1">

  <div id="div2"></div>

   </div>

</body>

</html>

原因:盒子没有获得 haslayout  造成 margin-top无效

 

解决办法:

1、在div1父层加上:overflow:hidden;

2、把margin-top外边距改成padding-top内边距 ;

3、父元素产生边距重叠的边有不为 0 的 padding 或宽度不为 0 且 style 不为 none 的 border。

    div1加: padding-top: 1px; /* 或 border-top: 1px solid red; */

4、让父元素生成一个 block formating context,以下属性可以实现
    * float: left/right
    * position: absolute
    * display: inline-block/table-cell(或其他 table 类型)
    * overflow: hidden/auto

   div1加:position: absolute; /* 或其他可生成 block formating context 的属性 */

分享到:更多

相关推荐

发表评论

路人甲 表情
看不清楚?点图切换 Ctrl+Enter快速提交

网友评论(2)

太好了 问题解决了,谢谢
网站建设 12年前 (2012-05-15) 回复
@网站建设:呵呵,不客气,解决就好,这里很多问题都是我碰到过,所以记录了下来,希望能帮到有需要的人
sysdee 12年前 (2012-05-19) 回复