div嵌套引起的margin-top不起作用

嵌套div中margin-top转移问题的解决办法

在这两个浏览器中,有两个嵌套关系的div,如果外层div的父元素padding值为0,那么内层div的margin-top或者margin-bottom的值会“转移”给外层div。

<!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>无标题文档</title>
</head>

<body>
<div style="background-color:#FF0000;width:300px; height:100px">上部层</div>

<div style="background-color:#009900; width:300px; height:300px;overflow:hidden "> <!--父层-->
         <div style="margin:50px; background-color:#000000;width:200px; height:200px"">子层</div>
</div>

</body>
</html>

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

 

解决办法:

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

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

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

    父层div加: padding-top: 1px;

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

     父层div加:position: absolute;
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值