问题
HTML:
<div id="wrapper">
<div id="content">
<div id="slider"></div>
<div id="left"></div>
<div id="right"></div>
</div>
</div>
CSS:
#wrapper
{
background:blue;
width:990px;
margin:0 auto;
}
#content
{
width:990px;
height:auto;
}
#slider
{
width:990px;
/* slider jquery */
height:auto;
}
#left
{
float:left;
width:490px;
}
#right
{
float:right;
width:490px;
}
Live demo: Tinkerbin
But in left and right div blue color is not displaying ,
If i am giving overflow:hidden
to wrapper
then its work fine.
Is it necessary to give overflow
to parent of floating div?
why?
回答1:
One of the common problems we face when coding with float based layouts
is that the wrapper container
doesn't expand to the height of the child floating elements.
The typical solution to fix this is by adding an element with clear float after the floating elements or adding a clearfix to the wrapper
. But you can also use the overflow property to fix this problem
. It's not a new CSS trick either. It's been documented before long long ago.
回答2:
When you float an element it appears as if it's lost it's height. So element is in blue color, you just don't see it. Either you give him height, or style your wrapper with overflow: hidden
. And if you want background color for elements it's background-color: blue
. color: blue
is for letters.
回答3:
You have to use the clearfix if you have floating elements inside a <div>
.
The problem happens when a floated element is within a container box, that element does not automatically force the container’s height adjust to the floated element. When an element is floated, its parent no longer contains it because the float is removed from the flow.
<div id="wrapper">
<div id="content">
<div id="slider">slider</div>
<div id="left">left</div>
<div id="right">right</div>
<div class="clear"></div> <!-- THIS -->
</div>
</div>
.clear { clear: both }
Live demo: Tinkerbin
来源:https://stackoverflow.com/questions/11709433/floating-div-not-displaying-background-color-when-i-am-not-using-overflow