我们使用 div 布局时,少不了使用 float,假如我们有这么一个布局:一行里面有两列,这一行的背景是红色,左边一列的背景是青色,右边一列的背景是蓝色,我们看看如下的代码:
<div style="background-color:#FF0000;">
<div style="float:left;width:100px;height:100px;background-color:#009999;">左列</div>
<div style="float:left;width:100px;height:50px;background-color:#000099;">右列</div>
</div>
由于右边一列的高度与左边一列的高度少 50px,按我们的要求,没有被遮住的地方应该显示出大背景--红色,即如下效果:
但实际上,我们会发现根本没有红色的那一块,即外层 div 的宽度或高度为 0,这在 IE、Netscape、Opera、Firefox 中均是相同表现。
我们再使用如下代码:
<div style="width:200px;background-color:#FF0000;">
<div style="float:left;width:100px;height:100px;background-color:#009999;"> </div>
<div style="float:left;width:100px;height:50px;background-color:#000099;"> </div>
</div>
成功了,可以看到红色块了,也就是说背景效果出来了。但别高兴得太早,这只是在 IE 和 Opera 中有效,在 Netscape 和 FireFox 里仍然看不到红色块的,真是多事,使用如下代码解决:
<div style="width:200px;">
<div style="float:left;background-color:#FF0000;">
<div style="float:left;width:100px;height:100px;background-color:#009999;"> </div>
<div style="float:left;width:100px;height:50px;background-color:#000099;"> </div>
</div>
</div>
在列与外层 div 之间加一层 div(红色代码),为这层 div 指定背景作为该行的背景,同时一定要为该 div 指定:float:left;。
一切似乎都很完美,然而,请再使用如下代码:
<div style="width:200px;">
<div style="float:left;background-color:#FF0000;">
<div style="float:left;width:100px;height:100px;background-color:#009999;"> </div>
<div style="float:left;width:50px;height:50px;background-color:#000099;"> </div>
</div>
</div>
我们将右边块宽度改为 50px,现在在 IE、Netscape、Opera、Firefox 中表现均是如下现象,注意红色背景变窄了:
我们再测试一下,把右列的 float 属性值改为 right,此时 IE、Netscape 和 Firefox 中红色背景宽度均是 200px(有 100px 被青色覆盖),而 Opera 中宽度仅为 150px(有 100px 被青色覆盖)。
背景宽度并没有体现出来,如下代码解决:
<div style="width:200px;">
<div style="float:left;width:100%;background-color:#FF0000;">
<div style="float:left;width:100px;height:100px;background-color:#009999;"> </div>
<div style="float:left;width:50px;height:50px;background-color:#000099;"> </div>
</div>
</div>
总结
如果子块有浮动,同时母块要使用背景,那么应该:
上面母块和添加的 div 均指定了 width,是不是可以把母块的 width 省略了呢?不建议您这样做,因为如果母块又是另一个大母块的子块,同时设定了边距,那么在 IE6 中,很可能出现宽度超出预期的情况,具体就不演示了。大多数情况下,我们为添加的 div 指定 width 属性值时用百分比。