Quick Tip: Clear CSS Floats

I notice a lot of people like to float elements all the time but don’t clear them correctly. I’ll shed a little insight on this in the future but for now, here’s a quick snippet of code that I use all the time to clear css floats.

The css snippet is as follows:

.clear:before,
.clear:after {
   content:"";
   display:table;
}
.clear:after {
   clear:both;
}
.clear {
   zoom:1; /* For IE 6/7 (trigger hasLayout) */
}

The semi-serious explanation of how and why to use this.

Most people when floating and clearing an element write code similar to the following:

<div id="parentDiv">
   <div class="float:left"></div>
   <div class="float:right"></div>
   <div class="clear"></div>
</div>

The issue with this is you have to add an unnecessary empty tag everywhere. When you have a lot of elements floating you can see how this can quickly start to get frustrating.

So instead, to fix your floating woes, add the above css to your style sheet, and rework the code as follows:

<div id="parentDiv clear">
   <div class="float:left"></div>
   <div class="float:right"></div>   
</div>

Tada! Just add the clear class to the parent div. Now you just learned an incredibly easy way to clear css floats!

Resource: css tricks

Want to earn an extra $30,000 this year?

Me too! And guess what? I'm almost there already and it's only April! Check out what I'm doing here.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>