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();
}

Jake Bresnehan

A Front End Developer based in Sydney and the creator of Web Design Weekly.

Web Design Weekly keeps developers at the forefront of techniques and trends whilst helping them learn and grow to produce top quality code to make the web a better place for all.

4 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.

    • I found that using @extend within a media query kicked up an error since I last updated Sass:

      - @extending an outer selector from within @media is deprecated.
      – You may only @extend selectors within the same directive.
      – This will be an error in Sass 3.3.
      - It can only work once @extend is supported natively in the browser.

      Replacing it with this mixin worked a treat!

This post currently has 4 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 *

Current day month ye@r *