A better way to clear float using a clearfix class



Today I will show you how to clear a float in CSS, the better way!

Suppose you have a container, which has a border, or a background color. Inside of that div you have some text and maybe some images. You want to float the images to the left, however if you do that your elements will be going outside of your container.

Take the following sample HTML and CSS code.

HTML
<div id="container">
 <p>Some content.</p>
  <img src="http://placekitten.com/150" class="pull-left">
  <img src="http://placekitten.com/150" class="pull-left">
  <img src="http://placekitten.com/150" class="pull-left">
  <img src="http://placekitten.com/150" class="pull-left">
</div>
CSS
#container {
 width: 450px;
 margin: 20px auto;
 border: 2px solid #cccccc;
 padding: 10px;
}

.pull-left {
 float: left;
}

This HTML and CSS would give the following result, where your content goes outside of your container div.

Bad floating

Bad floating elements, going outside of the container div.

Fixing the elements by clearing the float

One way which is very common to fix this is by adding an empty div with a clear:both property on it like this.



<div id="container">
 <p>Some content.</p>
  <img src="http://placekitten.com/150" class="pull-left">
  <img src="http://placekitten.com/150" class="pull-left">
  <img src="http://placekitten.com/150" class="pull-left">
  <img src="http://placekitten.com/150" class="pull-left">

  <div style="clear: both;"></div>
</div>

However, a much more preferred way would be to make a clearfix class. You can then use the pseudo-class selector :after to clear the float.

.clearfix:after {
  display: block;
  clear: both;
  content: "";
}

This way, you can apply this class to any container you like, which has floating elements inside. This also prevents your HTML from getting cluttered up with a lot of the same divs just for clearing floats. Once you have added this CSS, clearing the floating elements is as easy as adding the class to the container.

<div id="container" class="clearfix">
 <p>Some content.</p>
  <img src="http://placekitten.com/150" class="pull-left">
  <img src="http://placekitten.com/150" class="pull-left">
  <img src="http://placekitten.com/150" class="pull-left">
  <img src="http://placekitten.com/150" class="pull-left">
</div>

And here is the result:

Container div with floating elements cleared

Container div with floating elements cleared

That’s it!

I hope this helped you out, whether you were searching how to clear a floating element, or you wanted to know how to make the clearfix class. If you were using the old way, you will soon realize that this way is much faster and cleaner.

Share the knowledge!
Share on Facebook0Tweet about this on Twitter0Share on Google+0Share on StumbleUpon135Share on Reddit0Share on LinkedIn0Share on TumblrBuffer this pageDigg this

Comments

You may also like...

Stay updated
Subscribe!