CSS clearfix leaves space below container
I’ve been using clearfix to clear floats for years now, and I always knew that it left a little bit of space after the HTML container that is was applied to. Most of the time I sort of worked around it, but I was curious whether there was a better solution.
Turns out, there is.
The problem is actually with the content
of .clearfix:after
:
.clearfix:after {
content: '.';
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
The period is appended and hence there is a bit of a padding. The way to work around that is to simply change the period into a space, which isn’t rendered by the browser, and hence there’s nothing added to the end of your HTML container.
The complete clearfix then looks like this:
.clearfix:after {
content: ' ';
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
.clearfix {
display: inline-block;
}
html[xmlns] .clearfix {
display: block;
}
* html .clearfix {
height: 1%;
}
This solution worked beautifully.
Featured image by Michael Dziedzic.