Floating div not displaying background color when i am not using overflow?

不问归期 提交于 2019-12-19 10:35:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!