Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS background disappears when using float:left [duplicate]

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?

like image 813
UpCat Avatar asked Mar 02 '12 18:03

UpCat


3 Answers

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

like image 79
j08691 Avatar answered Nov 09 '22 16:11

j08691


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.

like image 31
animuson Avatar answered Nov 09 '22 17:11

animuson


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.

like image 4
Sparky Avatar answered Nov 09 '22 16:11

Sparky