div不设置高度背景颜色或外边框不能显示

来源:互联网 发布:淘宝中评可以改差评吗 编辑:程序博客网 时间:2024/06/06 08:25

针对这种问题,是因为各个浏览器的w3c标准不同,造成的不同浏览器之间的差异问题:

1.首先贴上代码:

<!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><style>.fotio{background:#0000CC; zoom:1; /* IE */}.fotio:after {content:".";height:0; line-height:0; font-size:0; }.ovosudsaca{ float:left; height:100px; width:200px; background:#CCCCCC;border:1px solid red;}</style></head><body><div class="fotio"><div class="ovosudsaca"></div><div class="ovosudsaca"></div></div></body></html>

在IE7中显示的结果是:


最外层的div显示是正常的,背景颜色可以显示出来,但是在IE8,IE9和火狐中显示的结果是:

这是因为里面的DIV是浮动的(float)而母体不会去计算子体float之后的height。而在IE6/7中支持这种计算,所以IE下正常。

所以出现这种问题有两个前提:

1.外部div没有设置高度;

2. 内部div是浮动的(带有float属性)。

那么解决方案就是:给外层的div设置高度(不推荐),因为只有在确定外层div的高度是多少的时候,这种方法才是可取的,但是大多数情况下,我们都希望外层div能够自动计算内部div的高度,然后填充,所以

方法一:

在内部最后一个FLOAT的div后加一个清除浮动(推荐),这样firefox和IE8/9就把里面不当成浮动,会自动计算内部div高度

<div class="fotio"><div class="ovosudsaca"></div><div class="ovosudsaca"></div><div style="clear:both;"></div></div>

方法二:(这种方法是百度的时候从别人的博客中看到的,我试过,挺管用)在最外层div中加入属性"overflow:hidden;";

 

<!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><style>.fotio{background:#0000CC;overflow:hidden; zoom:1; /* IE */}.fotio:after {content:".";height:0; line-height:0; font-size:0; }.ovosudsaca{ float:left; height:100px; width:200px; background:#CCCCCC;border:1px solid red;}</style></head><body><div class="fotio"><div class="ovosudsaca"></div><div class="ovosudsaca"></div></div></body></html>