Clearing CSS Floats Without Markup

This has done the rounds loads of times before - but clearing css floats is something I need to do all the time, and since I have to look up the code on every project I thought I would add it here so that I have a reminder.

This method uses css pseudo elements to do the clearing without adding random elements that contain 'clear:both;' which in turn means that the html is kept nice and clean and the css doesn't interfere with anything else.

.clear{zoom:1;}
.clear:after{content:" ";display:block;visibility:hidden;clear:both;}
.clear:before{content:" ";display:block;visibility:hidden;}

Since I also use it with LESS here's how I do that:

.clear {
	zoom:1;
	
	&:after {
		content:" ";
		display:block;
		visibility:hidden;
		clear:both;
	}
	&:before {
		content:" ";
		display:block;
		visibility:hidden;
	}
}

To use this just add the clear class to the element you want to clear.

<div class="clear">
<div class="float">Floaty thing here</div>
<div class="float">Floaty thing here</div>
</div>

CSS Pen image from Shutterstock

Share This...

About The Author

Ben Gillbanks

Web Designer, Video Gamer, Blogger, and part time Entrepreneur. Read More

4 thoughts on “Clearing CSS Floats Without Markup

  • Reply ›
    Anton

    Each time I'm using the same method on my blog. For me it is the most "comfortable"

    November 27, 2012

  • Reply ›
    Robert Wilkins

    Ben, this looks very cool and I'm all in favor of using less code and saving time. Can you show a brief example of what the html would look like. Do you add .clear to a content element?

    Now you can see I don't understand...

    Thanks,
    Bob

    March 15, 2013

    • Reply ›
      Ben

      Hi Robert - yeah, just add clear as the css class for the container of the floated items. I've added a small sample to the code above :)

      March 18, 2013

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="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Websites linking here

  1. Favicon for http://www.google.com/s2/favicons?domain=bengillbanks.co.uk Clearing CSS Floats Without Markup

My Projects

TimThumb - Image Resize Script TimThumb

Image Resize Thumbnail Script

WPVote - WordPress Social Voting WPVote.com

WordPress Social Voting Site

About me

About BenMy name is Ben Gillbanks. I'm a lover of Video Games, WordPress, Web Development and everything in between.

I have been working on the internet since 1998, and working with computers even longer. I am a hardcore Nintendo fanboy and have owned most of their consoles at one stage or another.

Read more about me on my about page.

My Tweets › Binary Moon

Random Link-outs

Keep Updated

Subscribe to RSS

Stay Updated

Binary Moon

WordPress and Web Development › home of Ben Gillbanks