SASS的混入顺序

时间:2019-07-18 17:52:08

标签: css sass

我如何让SASS尊重mixin的顺序:

SASS输入:

@mixin containerMargins {
  margin: 4rem 10vw;


    @media only screen and (min-width: 768) {
        margin: 7rem 10vw;
    };

    @media only screen and (min-width: 1024) {
        margin: 7rem 20vw;
    };
}

.myContainer {
  @include containerMargins;
  margin-top: 0;
}

SASS输出:

.myContainer {
  margin: 4rem 10vw;
  margin-top: 0;  /* I want this to be at the bottom */
}
@media only screen and (min-width: 768) {
  .myContainer {
    margin: 7rem 10vw;
  }
}
@media only screen and (min-width: 1024) {
  .myContainer {
    margin: 7rem 20vw;
  }
}

所需的输出:

.myContainer {
  margin: 4rem 10vw;
}
@media only screen and (min-width: 768) {
  .myContainer {
    margin: 7rem 10vw;
  }
}
@media only screen and (min-width: 1024) {
  .myContainer {
    margin: 7rem 20vw;
  };
}
.myContainer {
  margin-top: 0;
}

我如何才能使利润排在最后?也就是说,mixin中的所有内容(包括@media查询)都应在margin-top之前。这可能吗?

3 个答案:

答案 0 :(得分:1)

我要去的最简单的方法是:

.myContainer { 
    @include containerMargins;
}
.myContainer {margin-top: 0; }

答案 1 :(得分:1)

我会为您的mixin创建参数,以便您可以为margin-top属性传递一个值:

@mixin containerMargins( $sm:'', $md:'', $lg:'' ) {
  margin: 4rem 10vw;
  margin-top: #{$sm};


    @media only screen and (min-width: 768) {
        margin: 7rem 10vw;
        margin-top: #{$md};
    };

    @media only screen and (min-width: 1024) {
        margin: 7rem 20vw;
        margin-top: #{$lg};
    };
}

.myContainer {
  @include containerMargins('','','0');
}

这将输出:

.myContainer {
  margin: 4rem 10vw;
}
@media only screen and (min-width: 768) {
  .myContainer {
    margin: 7rem 10vw;
  }
}
@media only screen and (min-width: 1024) {
  .myContainer {
    margin: 7rem 20vw;
    margin-top: 0;
  }
}

如果将@include containerMargins();参数保留为空,则会输出以下CSS:

.myContainer {
  margin: 4rem 10vw;
}
@media only screen and (min-width: 768) {
  .myContainer {
    margin: 7rem 10vw;
  }
}
@media only screen and (min-width: 1024) {
  .myContainer {
    margin: 7rem 20vw;
  }
}

那将不会影响margin-top属性。

答案 2 :(得分:0)

好像您在此处将速记顶部的倍数加倍:

margin:4rem //->顶部+底部10vw // //左+右->;

,然后添加“ margin-top:0;

尝试这样的事情:

@mixin containerMargins {

    @media only screen and (min-width: 768) {
        margin: 7rem 10vw;
    };

    @media only screen and (min-width: 1024) {
        margin: 7rem 20vw;
    };
}

.myContainer {
  @include containerMargins;
  margin-top: 0;
}

OR


@mixin containerMargins {
  margin: 4rem 10vw;

    @media only screen and (min-width: 768) {
        margin: 7rem 10vw;
    };

    @media only screen and (min-width: 1024) {
        margin: 7rem 20vw;
    };
}

.myContainer {
  @include containerMargins;
}

取决于所需的输出。