Div collapse after float css

2019-01-31 13:20发布

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;
}

9条回答
欢心
2楼-- · 2019-01-31 13:54

A few other options for clearing floats here:

http://www.quirksmode.org/css/clearing.html

http://www.sitepoint.com/blogs/2005/02/26/simple-clearing-of-floats/

As to the best way of doing it, that's almost a holy war, the purists would freak about the extra div, if you are not fussed by a little extra markup, the addition of the cleared div as suggested by Joshua and AJ will work fine, and is a reliable technique, but there are at least 17 other ways of doing it...

查看更多
迷人小祖宗
3楼-- · 2019-01-31 13:54

The quickest solution would be to add overflow:hidden to clear the float on the parent element:

#nav{overflow:hidden;}
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-31 13:56

Without changing your HTML:

#nav
{
    width: 100%;
    overflow: auto;
    border: solid 1px red;
}
#ulListNavi
{
    margin: 0;
    padding: 0;
    list-style: none;
}
#nav #ulListNavi li
{
    float: left;
}
#nav #ulListNavi li a
{
    margin-left: 5px;
}

Works in IE8 and FF 3.5

查看更多
一纸荒年 Trace。
5楼-- · 2019-01-31 14:07

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; }
查看更多
狗以群分
6楼-- · 2019-01-31 14:07

Don't bother with clearing elements or overflow. Add this:

#nav {
    float: left;
}

When you float the LI's, the #nav no longer "contains" anything so it collapses. But if the #nav is floated also, it contains anything floated inside it, so it expands again.

(Also consider removing the #nav div and just applying the same styles to the UL.)

查看更多
姐就是有狂的资本
7楼-- · 2019-01-31 14:10

add this code after your ul:

<div style="clear: both"></div> 
查看更多
登录 后发表回答