Quick Tip #1 – Clearing Floats without extra Tags

14 Apr 2009 3 Comment

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
  • http://coolgarriv.com Dave Meehan

    Looking forward to reading more CSS tips, and the jQuery ones too.

  • http://www.hybridanime49.com hybridanime49

    Great tips! I have a question. When i post some of my blogs, the right sidebar tends to be pushed down below my postings. Whats the solution for it?

  • http://miralize.com Sean O’ Grady

    Thats probably due to extra padding or margins.. make sure that your padding and width etc.. add up to the desired width of your sidebar