<ul> height when containing floating <li>
Asked Answered
A

4

32

I have a list:

<ul>
 <li>Number 1</li>
 <li>Number 2</li>
 <li>Number 3</li>
 ...
</ul>

All the <li> are floating. I need the height of the <ul> box. If I remember correctly this is not valid:

<ul>
 <li>Number 1</li>
 <li>Number 2</li>
 <li>Number 3</li>
 ...
 <hr class="clear" />
</ul>

.clear {
   clear: both;
}

How can I do this? The number of items in the list can be different so I can't use fixed height.

Alicia answered 19/7, 2011 at 17:21 Comment(1)
When you float "ALL" the elements in a containing element, the containing element height collapses and does not "wrap" around the floated element. Many ways around this. Adding overflow: auto to the containg element solves the probelm. Adding extra element at the bottom alos solves the problem.Ruhr
C
63

Good options to contain the floats:

Cauterant answered 19/7, 2011 at 17:25 Comment(5)
thank you and thx for the links as well I would google it anyway :)Alicia
Thanks for the answer. I don't get the logic of why this works. One would think that overflow: hidden would do the oppositeOresund
also why does the containing element not wrap around the float elements ? So why does the ul not wrap around the floated li elements ?Vegetarianism
clearfix is enough.. no idea why someone would add overflow:hidden to the ul in this case lol ^^Mera
@Vegetarianism #3401249Vd
C
3

This isn't a direct answer to your question, but as an alternative could you consider using display:inline-block? These days I just use that instead of float where possible, as essentially most of the time it can achieve the same sort of objective without the total hassle of making containers properly contain inner floating elements and having to clear them all the time.

Custard answered 19/7, 2011 at 17:26 Comment(2)
inline-block is a valid option, but it has it's own (solvable) downsides such as being affected by whitespace in the HTML, and not working in IE7 without messing around.Cauterant
Ah, understood. I must confess that I have the luxury of being able to ignore older browsers like IE7 because what I do is kind of specialised stuff whereby the browser used by the end user is kind of known and controlled. It was worth a mention anyhow.Custard
W
1

test it:

ul { overflow: hidden; }
li { float:right; display:block; }

add class to your elements, don't do this for all elements.

Wangle answered 5/9, 2013 at 10:51 Comment(0)
P
1

Here, i am presenting, one of the easiest way to handle this kind of situations.

Float left always have some reaction and not good to use if we have some alternative of it.

The Alternative is :

li { display:inline-block; }

No need to add extra code like float:left and overflow:hidden :)

Papa answered 5/6, 2014 at 6:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.