有条件地否定Sass中的媒体查询

时间:2016-01-23 01:40:53

标签: sass

我有以下mixin(source):

@mixin media($queries) {

  @if length($queries) == 0 {
    @content;
  } @else {
    $first-key: nth(map-keys($queries), 1);

    @media ($first-key: map-get($queries, $first-key)) {
      $queries: map-remove($queries, $first-key);

      @include media($queries) {
        @content;
      }
    }
  }
}

我想使用一个条件来否定媒体查询,如下所示:

@media not screen and ($first-key: map-get($queries, $first-key)) {

动态添加它的正确语法是什么?我尝试了以下但没有成功:

$invert: true;
$foo: if($invert, 'not screen and', null);

@media #{$foo} ($first-key: map-get($queries, $first-key)) {

错误:

Invalid CSS after "...@media #{$foo} ": expected "{", was "($first-key: ma..."

迭代查询可能如下所示:

tablet: (
    respond-to: (min-width: 421px, max-width: 992px)
)

使用时会产生以下css:

@media (min-width: 421px) and (max-width: 992px) { }

1 个答案:

答案 0 :(得分:1)

我没有解释为什么你的东西不起作用(this issue声称插值是在解析媒体查询之前完成的。)

看起来您需要将and移到变量之外并进入媒体查询本身:

@mixin media($queries, $invert: false) {
  @if length($queries) == 0 {
    @content;
  } @else {
    $first-key: nth(map-keys($queries), 1);

    $foo: if($invert, 'not', '') screen;
    @media #{$foo} and ($first-key: map-get($queries, $first-key)) {
      $queries: map-remove($queries, $first-key);

      @include media($queries, $invert) {
        @content;
      }
    }
  }
}

输出:

@media not screen and (min-width: 30em) and (max-width: 50em) {
  .foo {
    color: red;
  }
}

@media (min-width: 30em) {
  .foo {
    color: green;
  }
}

是的,每次嵌套时都需要应用not,否则Sass不会合并媒体查询(您无法将not screen(min-width: 30em)合并,因为他们互相排斥。)