Sass Clearfix Mixin

There are a few ways to implement the clearfix hack but the following Sass Mixin has been in my toolbox for the last year thanks to this article on Nicolas Gallaghers blog.


@mixin clearfix() {
    &:before,
    &:after {
        content: "";
        display: table;
    }
    &:after {
        clear: both;
    }
}

Usage:


.article {
     @include clearfix();
}

3 Comments

  1. Great!! I wrote a code for .sass files – http://bit.ly/17XMmDT

  2. Using a placeholder class and extend would be better imo.

  3. I have not used this technique. This has been working for me well for a long time, I believe originally influenced by Chris Coyier?
    https://github.com/Toadstool-Stipe/stipe/blob/master/stylesheets/stipe/stipe/_mixins.scss#L268-L281

    But I agree with Johan, using this as a placeholder is a cleaner solution as always using the mixin will endlessly duplicate you code.

    If you look at the example I liked to above, this is a mixin. But I then use this as a placeholder selector
    https://github.com/Toadstool-Stipe/stipe/blob/master/stylesheets/stipe/stipe/_extends.scss#L6-L8

    In the end, in my final CSS I will do the following

    
    .block { @extend %clearfix }

    BTW – when you are creating or using a mixin without arguments, there is no need to include the empty parentheses `()`. That is an old trick with LESS to make a selector only act as a mixin.

This post currently has 3 responses. What do you think?

You can use basic HTML when posting code, please turn all < characters into &lt; or > into &gt;
If the code is multi-line, use <pre><code></code></pre>

Leave a Reply

Your email address will not be published. Required fields are marked *