Background disappears when my menu items are horizontal

Asked

Viewed 94 times

3

I have the following HTML code:

<div id="topo">
    <div id="menu">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Portfolio</a></li>
        <li><a href="#">Blog</a></li>
        <li><a href="#">Contato</a></li>
    </ul>
    </div>
</div>

And the following CSS:

#topo {
    background-color: #1a1e27;
    color:#FFFFFF; 
    width:950px;
}
#topo li {
    display:inline;
    float: left;
    margin-left: 5px;
} 

When I leave this code in one piece, it loses the background #1a1e27 but leaves my menu horizontal. When I take all the #topo li {}, it assigns the background color.

What I’m doing wrong?

  • 1

    @Bacco In fact, the problem can be reproduced only with the original code posted: http://jsfiddle.net/tZe4L/

  • @Rod now got the two colors right, see if that’s it.

2 answers

5


I noticed some problems: As you used display: inline, the float is not necessary, and how there is a <a>, the white color of <li> is having no effect.

This css solves both problems:

#topo {
   background-color: #1a1e27;
   width:950px;
}
#topo li {
   display:inline;
   margin-left: 5px;
}
#topo a {
   color:#FFFFFF; 
}
  • @mgibsonbr now that I realized the float :)

  • 1

    Great, that works too. Demo: http://jsfiddle.net/tZe4L/2/

  • yeah, that time I was scratching on the fiddle that @mgibsonbr posted, and that’s when I noticed the remaining float :)

  • Thank you Bacco, then float, only works in block elements

  • @Rod No, float works on any element, and float elements are treated as blocks.

3

When you float the elements inside a container, it behaves as if it were empty - so no dimensions, and no background. The solution is to put overflow: hidden in the container to "clean" the floats. Also note that float: left nullifies its display: inline. CSS can then stay like this:

#topo {
    background-color: #1a1e27;
    color:#FFFFFF; 
    width:950px;
    overflow: hidden;
}
#topo li {
    float: left;
    margin-left: 5px;
} 

http://jsfiddle.net/tZe4L/1/

Or, as Bacco suggested, you can put your <li> inline, without floating them.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.