KaZyKa
KaZyKa

Reputation: 325

why does "float" in css ruin the background color

When I use this, then the background-color works

    header {
        background-color: #bab615;

    }
    nav {
        background: #f96e5b;
        width: auto;
    }
    nav ul {
        list-style: none;
        margin: 0;
        padding: 0;
        line-height: 1;
        display: block;
        zoom: 1;
    }

but if I add a float to "nav ul" e.g. float: left; then it makes the background color of both elements white... Why?

     header {
        background-color: #bab615;

    }
    nav {
        background: #f96e5b;
        width: auto;
    }
    nav ul {
        list-style: none;
        margin: 0;
        padding: 0;
        line-height: 1;
        display: block;
        zoom: 1;
        float: left; <---This
    }

Edit: changed #cssmenu to nav, since it is a nav in the html Edit#2: jsfiddle.net/5vjor56y

Upvotes: 4

Views: 898

Answers (3)

Just simply put overflow as hidden on the parent element. It will work for you.

overflow:hidden;

Upvotes: -1

timothym
timothym

Reputation: 3275

It sounds like you need to clear the floated elements within nav.

You can do this within the css like so:

nav {
  overflow: hidden;
}

This is where the "clearfix" comes into play. It's another way to do the above:

.nav:after {
  content: "";
  display: table;
  clear: both;
} 

The clearfix is probably the best way to do this, as you don't need to create html elements whose sole purpose is to clear floated elements. For a deeper understanding of why this must be done, see this css tricks article.

Upvotes: 3

Patrick Moore
Patrick Moore

Reputation: 13344

You need to clear floats.

<div style="clear:both;"></div>

or

<br clear="all" />

are two common ways. This should be placed immediately following the closing tag of the floated element(s), i.e.:

<nav>
    <ul>
    <li><a href="#"></a></li>
    <li><a href="#"></a></li>
    <li><a href="#"></a></li>
    </ul>
    <div style="clear:both;">
</nav>

Upvotes: 1

Related Questions