Quick Tip #1 – Clearing Floats without extra Tags
This is going to be my first CSS snippet. I am going to post a series of both symantic and useful CSS tips. These will be good for both beginners and people who might know CSS already, but are looking for more efficient ways of handling their code. My first tip will be a very useful method of clearing floats in CSS only, without the need for excessive xHTML tags.
Here is how the xHTML is marked up
[html]<div id="container">
<div id="columnOne">Column 1</div>
<div id="columnTwo">Column 2</div>
<!– remove this if you have to use the wrong method <br /> –>
</div>[/html]
Usually you would just have a clearing line break or div to clear them but there is a much simpler solution. My CSS is as follows
[css]/* Right Method */
#container {width:960px; overflow:hidden;}
#columnOne {width:660px; float:left;}
#columnTwo {width:300px; float:left;}
/* Wrong Method */
.clear {clear:both;}[/css]
The trick is to set a fixed width on the parent div and have overflow set to hidden. Then your floats will be automatically cleared without using the old method
Final thoughts
Pros:
- No extra markup
- More symantic
Cons:
- Bad if you need to leave the width automatic