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>
Was it good/ useful/ a load of old rubbish? Let me know on Mastodon, or BlueSky (or Twitter X if you must).
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.