Sass/SCSS Mixin for Clearfix - 最佳方法?

Ric*_*dan 10 sass mixins clearfix ruby-on-rails-3.1

我想clearfix从我的HTML中删除该类,并在我的SCSS(Rails 3.1应用程序)中包含clearfix mixin.对此最好的方法是什么?

我正在考虑将HTML 5 Boilerplate clearfix转换为mixin,然后在CSS中包含需要clearfixing的元素.

从HTML5 Boilerplate复制:

/* The Magnificent Clearfix: Updated to prevent margin-collapsing on child elements. http://j.mp/bestclearfix */
.clearfix:before, .clearfix:after { content: "\0020"; display: block; height: 0; overflow: hidden; }
.clearfix:after { clear: both; }

/* Fix clearfix: blueprintcss.lighthouseapp.com/projects/15318/tickets/5-extra-margin padding-bottom-of-page */
.clearfix { zoom: 1; }
Run Code Online (Sandbox Code Playgroud)

这有缺点吗?有没有更好的办法?我可以通过这种方式安全地从我的HTML标记中删除clearfix吗?

Ric*_*dan 31

我应该补充一下 - 这是我提出的解决方案.我仍然对这一切都很陌生,所以我不知道这是否实际上与将元素的类设置为clearfix并使用上面的HTML5样板代码完全相同.

@mixin clearfix {
    zoom:1;
    &:before, &:after {
        content: "\0020"; 
        display: block; 
        height: 0; 
        overflow: hidden; 
    }
    &:after {
        clear: both;
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑: 最好使用@extend而不是mixin,因为它会产生更少的CSS代码.此外,使用时使用静默类(表示为%)很有用@extend.这可以防止意外的CSS规则,并且如果没有直接使用,则会删除您正在扩展的规则.

%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;
}
Run Code Online (Sandbox Code Playgroud)


Vol*_* E. 12

要通过使用来实现更少的代码输出@extend,请将clearfix定义为占位符(这里仅适用于没有IE 6 + 7的现代浏览器):

Sass代码:

%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;
}
Run Code Online (Sandbox Code Playgroud)

CSS输出将是:

#container:after {
    content: " ";
    display: block;
    clear: both;
}
#container {
    position: relative;
    min-width: 42.5em;
}
Run Code Online (Sandbox Code Playgroud)