Clearing a floated <li> correctly
Asked Answered
A

3

6

i dialy deal with float: left; and the CSS-reset by Eric Meyer with class="clearfix". But there is one special case, i wonder how to clear a floatd element correctly: Within <ul> ... </ul>.

Wrong height of the <ul> though using a clearer. The clearer should be within the <ul>. Let's try ...

Correct height, but the HTML-code ist not valid!

How can i clear the float within the <ul> with valid code?

Thanks, Johannes

Atomize answered 5/2, 2011 at 0:3 Comment(2)
Just a hint, but if you're talking code it often helps to post the relevant code here and, ideally, posting a live demo at JS Fiddle, or JS Bin, (or other similar site) for us to play with, so we can see what's happening.Casanova
Here is the code: linkAtomize
H
23

Simply add overflow: hidden to the ul element's ruleset. Search for 'clearing floats' on Google or Stack Overflow for other solutions, though in this case this should be the cleanest.

jsfiddle demo: http://jsfiddle.net/9sxrN/1/

Headstall answered 5/2, 2011 at 0:51 Comment(5)
Thakn you very much. That works. But i don't understand, why overflow: hidden; does solve the problem. I thought, that i neccessarily have to apply cleat: left; when i use a float: left;??Atomize
@Yi Jiang I too am curious about why overflow solves. I do know it flags the element with a special property but couldn't find a deep explanation.Roice
@Atomize @Roice @Yi Jiang did anyone ever figure out why ul overflow:hidden solves the clearing issue? Very mysterious.Rapport
This seems like a mistake in the implementation of overflow and ul but at least it works. I hope it's a consistent mistake. Does anyone know if it is or not?Catechist
It is not a mistake, it works with all elements, you do however loose the ability to, well overflow anything like absolutely positioned tip of the tooltip etc.Intercalary
M
0

As I understand, float can be applied to block-elements, that can't be inserted in UL. (neither div, neither BR you can't insert in UL). In fact you can, but it isn't valid.

So, I covered your ul with div container:

<div class="ul-container">
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>
<br style="clear:both">
</div>
<b>The height of the ul-tag is ok, but the code is not valid!</b>

and css of ul a made css of .ul-container

.ul-container {
    border: 2px solid red;
}

ul li {
    float:left;
    background: #ccc;
    margin: 5px;
}
Musician answered 5/2, 2011 at 0:45 Comment(1)
Thank you, that works. But now there is a superfluously <div>-tag in the markup. For me is better, but not the perfect solution.Atomize
E
0

Use overflow:hidden; on the ul

Epithelioma answered 20/3, 2013 at 10:50 Comment(1)
This may answer the question,... can you flesh it out a bit ?Sporocyte

© 2022 - 2024 — McMap. All rights reserved.