首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > CSS >

(css margin有关问题)为什么里面对象的margin会“伸”到其所在容器之外啊

2012-11-12 
(css margin问题)为什么里面对象的margin会“伸”到其所在容器之外啊?代码非常简单,如下(xhtml strict类型):

(css margin问题)为什么里面对象的margin会“伸”到其所在容器之外啊?
代码非常简单,如下(xhtml strict类型):

HTML code
    <style type="text/css">                .t1{height:100px; width:200px; margin:0 auto; background:pink;            /*border:solid 0px red;*/            /*overflow:hidden;*/        }        .t1 .t2{margin:20px;border:solid 1px red;width:50px; height:50px;}    </style><body>    <div class="t1" >        <div class="t2"></div>    </div>    <div class="t1" >        <div class="t2"></div>    </div></body>

代码中里面盒子的margin“伸”出去了,也就是超出了其外面盒子的边界。
但是,如果将外面盒子加上一个边框,或加上overflow隐藏属性(代码中注释部分),都能够“正常表现”。
请高手释疑。

[解决办法]
嵌套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;

出处: http://blog.sina.com.cn/s/blog_6bec36f9010110w9.html
[解决办法]
可以参考下
http://www.w3school.com.cn/css/css_margin_collapsing.asp

热点排行