Sass Clearfix
March 2, 2014
Unlike positioning, floats are helpful for creating layouts without changing the flow of a web page.
If you don’t clear floats, however, they will misbehave. Un-cleared floats stack next to one another or collapse the height of their parent container if floated children elements are present.
Fortunately there’s a popular clearfix, made by Nicolas Gallagher
In the above example, you can see how it would look when all the elements properly clear—the height is no longer collapsed. Using a clearfix in this way, however, adds additional markup and creates a lot of repetitive CSS.
Sass Clearfix
Sass brings a bunch of benefits over plain ‘ole CSS like nesting and @extend
, which we can use to make a better clearfix. @extend
basically tells Sass that one selector should inherit the styles of another selector.
Sass supports the special placeholder selector %
, a silent class, which only compiles to CSS until we use it, eliminating repetitive CSS! You can use these to replace the class and id selectors.
By using Sass we end up with a much cleaner and simpler approach. We no longer have to add the clearfix class to our markup instead we just @extend
anywhere a clearfix is needed.