Could anyone explain when should the floated elements get cleared?
I have noticed sometimes when I make something in HTML, and I don’t clear them, it still all looks good!
Also can overflow:hidden be used as a replacement for clearing?
Look at this example:
<html>
<head>
<style>
.a { background-color: red; overflow: hidden }
.floated-left { float: left; width: 100px; height: 100px; background-color: blue; }
</style>
</head>
<body>
<p>div with class a, that does have overflow:hidden:</p>
<div class="a">
<div class="floated-left">Hi,</div>
<div class="floated-left">Mom!</div>
</div>
<p>i didn't clear anything</p>
</body>
</html>
Here I didn’t clear the floated divs, but set overflow:hidden for the .a class and the <p> below appeared in normal element flow.
However, if I removed overflow:hidden from the .a class, <p> gets displaced.
Please explain!
Thanks, Boda Cydo.
For block-level, non-replaced elements, when
overflowisn’t set to “visible” andheightisn’t “auto”, the element’s height depends on its descendents (CSS 2.1 § 10.6.6). Thus when you setoverflow: hiddenon.a, it stretches to contain the floated descendents. The<p>is below.a, so it’s below the floats.Without
overflow: hidden,.adoesn’t contain the floated children; its calculated height is 0. The<p>is still below.a, but not the floats. The floats push the inline content of<p>, as floats are wont to do.Try putting borders around
.aand paragraphs to more clearly see the difference.