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>

How was it for you? Let me know on BlueSky or Mastodon

(Please) Link to this page

Thanks for reading. I'd really appreciate it if you'd link to this page if you mention it in your newsletter or on your blog.

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...
03 Jun 2010

CSS Only Button – Redux

The other day, a post was published on Hongkiat showing how to make a button using CSS (Cascading Style Sheets) only. However, it was misleading as the CSS-only button also used JavaScript and an image or two. It was actually...
17 Feb 2024

Creating a Custom HTML Elements: A Colour Picker

I recently needed to create my first custom element - a custom color picker. I wanted to improve the color picker feature on Brush Ninja however I couldn’t find an existing solution that met my needs so I decided to...
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...
21 Oct 2018

Contributing to WordPress

In this article for WPTavern Chris Van Patten shares his experience with contributing to the Gutenberg project. The original article was a Twitter thread, but it’s nicer reading a proper long form piece.For Chris, the experience of contributing to Gutenberg...
13 Jul 2009

Fussing over the (web design) details

Having spent the last couple of months (on and off) messing around with the new Binary Moon design I am now at the stage where I want to say it’s finished and move on to something else.There’s a well known...