Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Div collapse after float css

I have a div called NAV and inside of NAV I have an UL with 5 li which I float to the left, the li's that is but when I do that the NAV collapses. I know this because I put a border around NAV to see if it collapses and it does. Here is the example.

collapsed http://img401.imageshack.us/img401/8867/collapsedze4.png

no collapsed http://img71.imageshack.us/img71/879/nocollapsedkx7.png

as you can see in the first image, the links in the NAV div are floated left and that black border ontop is the actual div called NAV.

in this image you can see how it has top and bottom border and it not collapsed.

here is some of the html and css I used.

alt text http://img301.imageshack.us/img301/5514/codejc8.png

#nav #ulListNavi  a  {
    float: left;
}
like image 858
user36682 Avatar asked Dec 16 '08 04:12

user36682


People also ask

How do you stop a div from collapsing?

There are many ways to prevent the parent of floated elements from collapsing in CSS: Method 1 (Using Overflow Property): We can use the overflow property of CSS to prevent the parents from collapsing. Set the value of the overflow property as “auto” for the parent and it will not collapse any more.

What causes container collapse CSS?

This happens because elements with float property are removed from the document flow so the sizes stay unknown for the parent element (as nothing is contained in it) so it is set to 0 .

What is a general rule we should use for floated elements to avoid messing up things?

"For one, the box being floated should have a width defined for it, either explicitly or implicitly. Otherwise, it will fill its containing block horizontally, just like non-floated content, leaving no room for other content to flow around it.


2 Answers

Add any overflow value other than visible to your container:

div#nav { overflow:auto; }

Then add width to restore the width

div#nav { width: 100%; overflow:auto; }
like image 101
Ken Avatar answered Sep 28 '22 07:09

Ken


One solution is to add a "clear:both" style to an element after the last floated anchor, for instance:

<div id="nav">
  <ul id="ulListNavi">
    <li><a href="#">Home</a></li>
    <li><a href="#">Search</a></li>
    <li><a href="#">Flowers</a></li>
    <li><a href="#">My Account</a></li>
    <li><a href="#">Contact Us</a></li>
  </ul>
  <div style="clear:both;"></div>
</div>

This causes the containing element to clear all floating elements before closing the containing box.

like image 43
Abram Simon Avatar answered Sep 28 '22 07:09

Abram Simon