Sass / SCSS Mixin for Clearfix - best approach?

前端 未结 4 680
情书的邮戳
情书的邮戳 2020-12-28 22:57

I want to remove the clearfix class from my HTML and include a clearfix mixin in my SCSS (Rails 3.1 application). What is the best approach to this?

相关标签:
4条回答
  • 2020-12-28 23:12
    // source http://www.alistapart.com/articles/getting-started-with-sass/
    // http://nicolasgallagher.com/micro-clearfix-hack/
    
        @mixin clearfix {
         // For modern browsers
          &:before,
          &:after {
            content:" ";
            display:table;
          }
    
          &:after {
            clear:both;
          }
    
          // For IE 6/7 (trigger hasLayout)
          & {
            *zoom:1;
          }
        }
    
    0 讨论(0)
  • 2020-12-28 23:33

    I should probably have added - this is the solution I came up with. I am still pretty new to all this so I don't know if this will actually do the same job as setting an element's class to clearfix and using the HTML5 boilerplate code above.

    @mixin clearfix {
        zoom:1;
        &:before, &:after {
            content: "\0020"; 
            display: block; 
            height: 0; 
            overflow: hidden; 
        }
        &:after {
            clear: both;
        }
    }
    

    Edit: It's best to use @extend instead of a mixin as it will produce much less CSS code. Also, it's useful to use a silent class (denoted by %) when using @extend. This prevents unexpected CSS rules and eliminates the rule you're extending if it's not being used directly.

    %clearfix {
        zoom:1;
        &:before, &:after {
            content: "\0020";
            display: block;
            height: 0;
            overflow: hidden;
        }
        &:after {
            clear: both;
        }
    }
    
    #head {
        @extend %clearfix;
        padding: 45px 0 14px; margin: 0 35px 0;
        border-bottom: 1px solid $border;
    }
    
    0 讨论(0)
  • 2020-12-28 23:33

    Why not use the Compass framework? It already provides mixins for clearfix among a host of other useful mixins and utilities. It's always better to look for existing tools rather than to have to maintain additional code yourself.

    0 讨论(0)
  • 2020-12-28 23:34

    To achieve less code output by using @extend, define clearfix as placeholder (here just for modern browsers w/o IE 6+7):

    Sass code:

    %clearfix {
        &:after {
            content: " ";
            display: block;
            clear: both;
        }
    }
    
    /* Use above defined placeholder in the selector(s) of your needs via @extend: */
    #container {
        position: relative;
        min-width: 42.5em;
        @extend %clearfix;
    }
    

    CSS output will be:

    #container:after {
        content: " ";
        display: block;
        clear: both;
    }
    #container {
        position: relative;
        min-width: 42.5em;
    }
    
    0 讨论(0)
提交回复
热议问题