21

This is my html:

<div class="header_wrapper">
       <div class="main_nav">
       <div>TEst</div>
       <div>TEst</div>
       <div>TEst</div>
    </div>
    <div class="clear"></div>
</div>

As you can see I want to build a menu with floating divs. Doing so the background of main_nav disappears.

.header_wrapper{

    height:129px;
    background:url('images/layout/header.png') no-repeat #1f1f1f;
    border-bottom:1px solid #1f66ad
}

.header_wrapper .main_nav{
    position:relative;
    top:77px; left:336px;
    width:750px;
    background:red;
}

.header_wrapper .main_nav div{
    float:left;
}

.clear{
    clear:both;
}

I tried to use clear:both, however the background is still gone. Any ideas why?

animuson
  • 53,861
  • 28
  • 137
  • 147
DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

4 Answers4

67

Adding overflow:auto; to main_nav brings the background back.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • Using _overflow:auto;_ can cause problems in some browsers like scroll bar may appear/disappear, or the content area my cut off – coderVishal Jul 04 '15 at 10:28
10

This is because floated content does not take up any space. Your parent main_div division essentially takes on a height of 0 because it has no other content, which "hides" the background (there is no height to display behind).

This information is available in the css-floating tag wiki and I've also posted other more detailed information about floating and parent containers.

Community
  • 1
  • 1
animuson
  • 53,861
  • 28
  • 137
  • 147
4

Put overflow on .main_nav

.header_wrapper .main_nav div{
    float:left;
    overflow: hidden;
}

Your clearing div forces its parent to expand, it has no effect on its sibling's background.

Sparky
  • 98,165
  • 25
  • 199
  • 285
3

You have to clear to your float DIV's parent which is .main_nav. Write like this:

.header_wrapper .main_nav{
  overflow:hidden;
}
sandeep
  • 91,313
  • 23
  • 137
  • 155