tags:

views:

61

answers:

2

I don't really understand what's going on here.

This is my css and html

#content {
    -moz-border-radius:10px;
    background:#F0F0F0;
    width: 910px;
    margin: 0 auto;
    clear: both;
}

#content ul {
list-style: none;
padding: 0;
margin: 0;
}

<div id="content">
  <ul>
    <li>Foo</li>
    <li>Bar</li>
    <li>Baz</li>
  </ul>
</div>

I obtain a grey box containing the items aligned vertically. I want to align them horizontally, and I read I have to put float: left in the #content ul selector. If I do so, the grey div box disappears, and the three li entries stay vertical. If I put the float: left to a #content ul li selector, the entries are now horizontal, but still the enclosing box disappears.

What am I missing ?

+2  A: 

Add a height to the UL along with your other css.

#content ul
{
    height: 20px;
}

#content ul li
{
    float: left;
}

OR you can use the following without a height on the UL

#content ul li
{
    display: inline;
}

OR you can put an element below the UL that clears.

CSS:

.clear
{
    clear: both;
    height: 1px;
}

HTML:

<ul>
    <li></li>
    <li></li>
</ul>
<div class="clear"></div>

OR (for good measure) you can add a height to the wrapping div

CSS:

.wrappingDiv
{
    height: 20px;
}

EXPLANATION: Floating elements are outside the normal flow of your content. Wrapping elements are therefore not "aware" of the floated elements height.

a432511
It works, thanks. But why do you need to specify the height ? Can't it determine it from the contents size ?
Stefano Borini
floated elements are outside the flow of the document and a wrapping div does not know that the floated elements have height. If you clear after it forces the containing div to have the appropriate height. There are several ways to resolve the issue. Another is height on the wrapping div. All of them work! Hope that helps you
a432511
oh... now I get it... thanks!
Stefano Borini
+4  A: 

floated elements don't actually force the container element to expand downwards to hold them (they'll float down past the bottom of the container). What you need to do is add an element after the list with clear:both as part of its style to force it down below the floats, and thus force the container's boundaries to expand below the floats. (Alternatively, you could set a fixed height for the container element.)

Amber