For years, variations on this have been my go-to CSS “clearfix” approach:
.clearfix::after { clear: both; content: ''; display: table; }
It’s the “conventional wisdom” on how to do this. But I found recently I was trying to do it and… it wasn’t working. In the middle of trying to figure out why it wasn’t working, it struck me that with modern CSS there’s probably a better way to do it. Why not this?
.clearfix + * { clear: both; }
It doesn’t require the trickery of creating an empty content block on a pseudo-element. It’s less code. It seems like exactly the kind of situation the CSS +
selector is intended for.
One little snag — although as I recall this was a snag with the old method too — is that it doesn’t introduce any spacing between the elements, and even putting a margin-top
on the latter element doesn’t have an effect, although padding
does.
So, it’s not ideal… or maybe there’s just something else I’m overlooking. But when is anything in CSS ideal? And how often isn’t there something I’m overlooking?