css - 从混合中合并选择器

标签 css sass compass-sass

我试图在单独的 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;}

最佳答案

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

你唯一真正能做的就是像这样(或者写 2 个单独的 mixins):

@mixin footer_flush_bottom {
    height: 100%;

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

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

关于css - 从混合中合并选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35157685/

相关文章:

css - 设计登录 css Ionic

html - 是否有一种 HTML/CSS 方法可以在不解析的情况下显示 HTML 标签?

javascript - 在#page HTML 链接顶部添加一个空格

html - 将元素定位到 block 元素的右侧

javascript - 使用 grunt-sass 编译基础 sass

html - css 中大于选择器的三倍是什么?

node.js - 如果此任务在该文件更改时启动,如何运行任务(更改文件)并避免循环

css - 帮助 Sass mixin 和变量(var 被忽略)

css - Sass中的双重插值(变量内部变量)

css - 如何在 sass 映射中使用多个值以及 mixin 中的每个函数