10

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

我正在考虑仅采用 HTML 5 Boilerplate clearfix 并将其转换为 mixin,然后将其 @include 到 CSS 中以获取需要 clearfixing 的元素。

复制自 HTML5 样板:

/* 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; }

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

4

4 回答 4

31

我可能应该添加 - 这是我想出的解决方案。我对这一切还是很陌生,所以我不知道这是否会与将元素的类设置为 clearfix 并使用上面的 HTML5 样板代码做同样的工作。

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

编辑: 最好使用@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;
}
于 2011-08-22T23:18:51.967 回答
12

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

萨斯代码:

%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 输出将是:

#container:after {
    content: " ";
    display: block;
    clear: both;
}
#container {
    position: relative;
    min-width: 42.5em;
}
于 2013-05-23T10:18:11.950 回答
4
// 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;
      }
    }
于 2012-08-03T09:01:41.440 回答
2

为什么不使用Compass框架?它已经在许多其他有用的 mixin 和实用程序中为 clearfix 提供了 mixins 。寻找现有的工具总是比自己维护额外的代码要好。

于 2011-08-23T20:02:01.793 回答