Using “overflow:hidden” instead of “clear:both”
I have noticed
that a lot of website developers use the “clear” method, when they want to stop
floating elements from messing up the structure bellow them. Or to make a
“Wrapping” outer div, adapt to the height of floating elements inside of it.
This method
requires you to write content-less elements in to the DOM, which is not clean.
Well, it’s valid, but can be done better! (:
In this
guide I will show you a batter way of doing it :D
Our test markup code (HTML)
<div class="wideWrapper">
<div class="floatingContent"></div>
<div class="floatingContent"></div>
<div class="floatingContent"></div>
<div class="floatingContent"></div>
<div class="floatingContent"></div>
<div class="floatingContent"></div>
<div class="floatingContent"></div>
<div class="floatingContent"></div>
<div class="floatingContent"></div>
<div class="floatingContent"></div>
<div class="floatingContent"></div>
<div class="floatingContent"></div>
</div>
Above we
have a “Wrapper” and some floating content.
Normally,
then our “Wrapper” would have a height that automatically fit’s the content and
therefore will make room for that content. But if our content is floating to
left or right, then our Wrapper will just collapse!
This will
also make our elements bellow the Wrapper come up behind the floating content,
because our wrapper won’t reserve space for the floating content (:
The solution without using the “Clear” method
.wideWrapper
{
width:613px;
position:relative;
top:0;
left:0;
margin:0 auto 0 auto;
border:solid 2px red;
overflow:hidden;
}
.floatingContent
{
float:left;
width:100px;
height:100px;
margin:10px;
border:solid 1px blue;
}
Much of the
style above is just to visualize this example (:
Starting at
line 1 we have the style for our Wrapper. The only important style here is the “overflow:hidden”.
This is our magic! (: Our Wrapper will now try to figure out how much of the
content inside are floating over the edge. And since our Wrapper doesn’t have a
static height defined, the our Wrapper will just gap over all of the floating
content.
Starting at
line 12 we have the style for our floating content (Our test content). The only
significant properties set here is the “float, width and height” Float set to
left to make our content float and the size properties to make our floating take up some space.
Done !