Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

css - Merging selectors from mixins

I'm trying to contain general styles/tricks in a separate mixin file which can be applied to any project when they're needed. Some of these styles require multiple elements to work together in order to work.

For example:

_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;
}

As it is, the mixin works but the generated css separates the mixin from the main code, even when their selectors are the same. The downside to this is ugly css and larger file size when I start including more of these.

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

Is there anyway I can do this so that same selectors can be merged? Like this:

/* 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;}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No. Sass has no way of merging selectors (this could be considered undesirable, as it would alter the ordering of the selectors).

The only thing you can really do is something like this (or write 2 separate 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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...