2011-12-05 90 views
10
<html> 
<head> 
<style type="text/css"> 
div 
{ 
background-color:#ccc; 
} 
</style> 
</head> 

<body> 
<div> 
<div style="float: left;">This is a text inside a div element.</div> 
<div style="float: right;">We are still in the div element.</div> 
</div> 

</body> 
</html> 

为什么在这两个div之间不显示背景颜色? Output after running this page带子div的背景颜色

回答

7

当你浮动元素时,你应该提供浮动元素的宽度。否则,您可能会遇到不同浏览器的意外行为。

Check this tutorial,有漂浮在CSS的很好的信息。 [链接已死]

基本上,如果你提供一个overflow:hidden;到容器div和提供宽度的浮动元素,你的问题将得到解决。

<div style="overflow: hidden;"> 
    <div style="float:left; width: 300px;">Some text</div> 
    <div style="float:right; width: 300px;">Some text</div> 
</div> 

同样,无论你想正常化流量IKE可以添加另一个DIV这样的:

<div> 
    <div style="float:left; width: 300px;">Some text</div> 
    <div style="float:right; width: 300px;">Some text</div> 
    <div style="clear:both;"></div> 
    <div>This div will be at the same place 
     as if the previous elements are not floated</div> 
</div> 

双方将工作:)

编辑

另一种方法,我在这几天经常使用的是浮动第一个元素,并将margin-left设置为以下元素。例如:

<div> 
    <div style="float: left; width: 300px;">Some text</div> 
    <div style="margin-left: 300px;">Some text</div> 
    <div style="clear: both;"></div> 
</div> 

该方法的优点是以下元素(在这种情况下的第二个div)不需要固定宽度。另外,你可以跳过第三格(clear: both;)。这是可选的。我只是添加它,以防浮动div的高度比第二个div长,因为如果您不添加它,父div将始终获得第二个div的高度。

6

只需将容器格设置为overflow: hidden;即可。

如果将元素设置为浮动,它们将不再处于文档的正常'流'中。

div { background: #ccc; overflow: hidden; } 

而且你甚至没有取得一个写意圆;)

2

这是因为无论是div s的浮动,从而含有div没有高度。如果您要添加第三个孩子div这不是浮动,请给它一个高度0clear:both您应该看到背景颜色出现。

+0

Yuck!尽可能不要使用'clear:both'黑客。几乎总是(/总是)更好的解决方案。 – PeeHaa

+0

我并不知道“overflow:hidden”技巧。 – Gareth

+0

看起来像你今天学到的东西:)为了完成我的评论和教育你更多;)当你想使用CSS3(例如拖放阴影)时,注意使用'overflow:hidden;'黑客。幸运的是,我们也有一个解决方案:http://fordinteractive.com/2009/12/goodbye-overflow-clearing-hack/ – PeeHaa

3

浮动元素不会影响父级的大小,除非父级特别包含使用overflow样式的子级。

您的外部div与子div具有相同的背景颜色,但父级的高度为零,因此您不会看到其背景。

1

您显示的空白区域是一个正文部分,您将背景颜色设置为div,但不在正文中。这是身体部分是空的原因。

颜色你应该添加以下代码空白部分:

<html> 
<head> 
    <style type="text/css"> 
div 
{ 
background-color:#ccc; 
} 
body{ 
background-color:#ccc; 
} 
</style> 
</head> 

<body> 
<div> 
<div style="float: left;">This is a text inside a div element.</div> 
<div style="float: right;">We are still in the div element.</div> 
</div> 

</body> 
</html> 

您可以通过改变车身造型的背景颜色改变身体的背景颜色。