2016-01-23 54 views
1
有条件地否定媒体查询

我有以下的混入(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 "[email protected] #{$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

我d没有解释你为什么不起作用(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))。

+0

谢谢,非常感谢 – Johan