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.

Writing with a pen

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>

Let me know what you think on Mastodon, or BlueSky (or Twitter X if you must).

Related Posts

25 Dec 2012

Learning to Accept CSS3: Creating CSS3 Windows

People are resistant to change. It’s strange since I consider myself quite forward thinking, but I still find it takes me a while to accept new things. I’ve been using CSS3 effects for quite a while now – as have...
29 Nov 2012

CSS Highlight Colour

When I design a website I really like to add small touches that most people won’t notice. In fact there’s a blog I follow that is dedicated to these small areas of delight. One of the things I like to...
20 Jul 2016

Empathy in Web Design

I wasn’t able to make WordCamp Europe this year, but they’ve been really quick at getting all of the talks online, and so I have been watching some of them – and this one stood out.Morten Rand-Hendriksen is an experienced...
19 Oct 2018

Smashing Book 6 Review: New Frontiers In Web Design

I really like the Smashing Magazine website. Unlike a lot of tutorial sites they don’t keep repeating the same basic content and focus on more challenging and newer things. So when I was contacted by Vitaly and asked if I...
08 Jul 2013

A Redesign for 2013

It’s only been a year since I last redesigned Binary Moon – I’m generally content to redesign, and then sit on things for a while, let it stew and evolve. However a lot has changed in the last year. Design...