Robert
Robert

Reputation: 10390

CSS floating elements causes other element background colors to disappear

I am testing out CSS and seeing how it works with floating elements in a horizontal menue:

<ul id="navlist">
    <li><a href="#">Item one</a></li>
    <li><a href="#">Item two</a></li>
    <li><a href="#">Item three</a></li>
</ul>

ul#navlist {
    list-style-type: none;
    margin: 0;
    padding: 0;
    background-color: cyan;
}
ul#navlist li {
    display: inline;
    background-color: pink;
}

/*ul#navlist li a {
    float:left;
}*/

I use the background colors to visually see what is affected. Here is the output:

output

Notice the left gap between the list items. Now when I un-comment/insert the the following line:

ul#navlist li a {
        float:left;
    }

The gap disappears (what I intended) but the background colors for both ul and li disappear. Output Why is this?

Upvotes: 0

Views: 125

Answers (1)

cvsguimaraes
cvsguimaraes

Reputation: 13240

The background is despairing because the content is floating, so the parent's height gets to zero. In practical terms, the link it's just anchored on the <li> and not inside it, got it?!

Change the <li> display type to inline-block and, optionally, set a height for your <li> elements.

Upvotes: 1

Related Questions