The float and clear problem confuses many web developers.
Suppose we have a layout like this:
What will happen it that the wrapper will not contain the two divs. Check out yourself by set the background color of wrapper.
There are several ways to fix this.
First way: clear: both
Add this code to the css:
And add this below the
The reason is that, if at the bottom, there are many
divs floated inside a wrapper
div, then these floated
divs will not extend the height(size) of the wrapper
div. Adding a clear
div at the bottom, with
clear: both, which means nothing allows to be floated on neither sides of it, solves the problem.
Second way: overflow
Back to original layout. We can add another style to the wrapper
This means, if anything
divs inside exceed the width or height, there will be a scroll bar.
If overflow is set to
hidden, it will not display the exceeding part. But
hidden also works for this problem.
Third way: clearfix
In the first way, adding a meaningless
div at the end of wrapper is a bad programming habit. To avoid this, here comes clearfix trick.
Add this to the style:
Apply clear to
This code means, with a clear class, an element will have a block at the end of the element. If you apply
clear to a
div, then it will have a block at the end of the
div has content, clear both left and right, like in the first way. It will display as a block, which by default is
auto. The block will not be visible, but it exists. The
height is 0px, so it will not take up space. We don’t need to put a clear div using HTML at the end of the element. Code is clean. Yeah.