【问题标题】:Merging selectors from mixins合并来自 mixin 的选择器
【发布时间】:2013-10-27 09:26:57
【问题描述】:

我试图在一个单独的 mixin 文件中包含一般样式/技巧,当需要时可以将其应用于任何项目。其中一些样式需要多个元素协同工作才能发挥作用。

例如:

_mixins.scss
====================
@mixin footer_flush_bottom {
    html {
        height: 100%;
    }

    body {
        min-height: 100%;
        position: relative;
    }

    #footer {
        position: absolute;
        bottom: 0;
    }
}

main.scss
====================
@import "mixins";

@include footer_flush_bottom;

html {
    background-color: $bg;
    //More stuff
}

body {
    margin: 0 auto;
    //More stuff
}

footer.scss
====================
#footer {
    height: 40px;
}

事实上,mixin 可以工作,但生成的 css 将 mixin 与主代码分开,即使它们的选择器相同。当我开始包含更多这些内容时,这样做的缺点是丑陋的 css 和更大的文件大小。

/* line 14, ../../sass/modules/_mixins.scss */
html {
  height: 100%; }

/* line 18, ../../sass/modules/_mixins.scss */
body {
  min-height: 100%;
  position: relative; }

/* line 22, ../sass/modules/_mixins.scss */
#footer {
  position: absolute;
  bottom: 0; }

/* line 19, ../../sass/modules/main.scss */
html {
  overflow-y: scroll; }

/* line 37, ../../sass/modules/main.scss */
body {
  margin: 0 auto;

/* line 1, ../sass/modules/footer.scss */
#footer {
  height: 40px;

无论如何我可以这样做以便合并相同的选择器吗?像这样:

/* line 19, ../../sass/modules/main.scss */
html {
  height: 100%;
  overflow-y: scroll; }

/* line 37, ../../sass/modules/main.scss */
body {
  min-height: 100%;
  position: relative;
  margin: 0 auto;

/* line 1, ../sass/modules/footer.scss */
#footer {
  position: absolute;
  bottom: 0;
  height: 40px;}

【问题讨论】:

  • 不幸的是,我不相信选择器可以合并。我不会太担心,GZIP 会压缩文件大小。

标签: css sass compass-sass


【解决方案1】:

没有。 Sass 无法合并选择器(这可能被认为是不可取的,因为它会改变选择器的顺序)。

你唯一能做的就是这样(或编写 2 个单独的 mixin):

@mixin footer_flush_bottom {
    height: 100%;

    body {
        min-height: 100%;
        position: relative;
        @content;
    }
}

html {
    // additional html styles
    @include footer_flush_bottom {
        // additional body styles
    }
}

【讨论】:

  • 我编写 mixin 的目的是使其可插入。编写单独的 mixin 或在 mixin 中使用“if”条件将需要我在每个选择器中调用 mixin,这有悖于它的目的。为了增加另一层复杂性,我不能按照你的方式做,因为代码的下一部分 - #footer - 位于其单独的文件中。也许我应该在问题中添加这一点。
猜你喜欢
  • 2021-06-09
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
  • 2023-03-24
相关资源
最近更新 更多