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

在Sass中有条件地否定媒体查询,sass,Sass,我有下面的mixin(): 我想使用一个条件来否定媒体查询,如下所示: @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

我有下面的mixin():

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

@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) { }

我没有解释为什么您所做的不起作用(声称插值是在解析媒体查询之前完成的)

看起来您需要将
移到变量外部,然后移到媒体查询本身中:

@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
(最小宽度:30em)
合并,因为它们相互排斥)。

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

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