IE中,当padding遇到margin...

首先看图:

代码:

<!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>IE中margin和padding的重叠</title>
<style type="text/css">
*
{margin:0; padding:0;}
.content
{padding:10px; background:red;}
.box
{margin:10px; background:green; height:100px;}
</style>
</head>
<body>
<div class="content">
<div class="box">margin:10px;</div>
</div>  
</body>
</html>
通过测试可以得知:IE8、火狐3.6.8、Google5.0、Opera10.61效果如左边,IE6、IE7、IE8(兼容模式)效果如右边。左边为期待效果。

经过研究,此为IE的hasLayout造成的,观上图,class为box的div,左边为白色尖括号,右边为橙色尖括号,证明在右边此div拥有布局。

为什么拥有布局以后是这个样子,我也不知道。以前总说怎样让IE拥有布局,这回要想怎样让IE取消布局。

首先,box的什么属性导致在IE8一下的版本拥有布局呢?

height:100px;

怎么解决呢,首先想到让他的父容器也hasLayout,于是第一次尝试:

.content{padding:10px; background:red; zoom:1;}
却出现了这样的情况:【IE6、IE7、IE8(兼容模式)】

在这三个浏览器下,上边依旧重叠,右下左回复正常。

第二次次尝试:

.content{padding:10px; background:red; overflow:hidden;}

得到的答案是IE7、IE8(兼容模式)下依旧只有上边不正常。IE6就恢复到最原始的状态,4个边全部重叠了。

第三次尝试:

.content{padding:10px; background:red; height:1%;}

和第一次尝试得到的效果相同。

其他尝试:

.content{padding:10px; background:red; min-width:0;}//第二种效果
.content{padding:10px; background:red; width:100%;}//第一种效果
……此处省略N多

还有一种另外,这个属于IE6的浮动问题了,具体看图片:

.content{padding:10px; background:red; float:left;}

改日继续吧!

先说一下目前我所知的完美的解决方案

一、可以给content加20px的padding而box的margin删掉,最简单,但是背离了这个问题的设计初衷;

二、多套一层div,也就是取消box的hasLayout;

<!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>解决IE中margin和padding的重叠</title>
<style type="text/css">
*
{margin:0; padding:0;}
.content
{padding:10px; background:red; float:left;}
.box
{margin:10px; background:green;}//删掉heiht
</style>
</head>
<body>
<div class="content">
<div class="box"><div style="height:100px;">多套一层div</div></div>
</div>
</body>
</html>
三、想办法让content也hasLayout,但目前的实验都是失败的。

原文地址:https://www.cnblogs.com/ShepherdIsland/p/IE_padding_margin_overlap.html