我可以使用媒体查询设置全局变量吗?

时间:2016-10-06 23:57:03

标签: css sass

我的代码味道如下:

$mobile-bg-color: #ddddff;
$desktop-bg-color: #ffdddd;
$mobile-border: solid 2px black;
$desktop-border: solid 2px red;



div {
    margin: 50px;       

    @media screen and (max-width: $mobile_threshold){

        background-color: $mobile-bg-color;
        border: $mobile-border;


    }

    @media screen and (min-width: $mobile_threshold + $threshold_step){

        background-color: $desktop-bg-color;
        border: $desktop-border;

    }

}

我必须在移动设备和桌面设备之间的任何地方进行此类操作。

我真正想做的是:

div {
    margin: 50px;
    border: $responsive-border;
    background-color: $responsive-bg-color; 
}

这可以使用Sass吗?

2 个答案:

答案 0 :(得分:1)

您可以使用mixin来实现此目的。像这样定义一个mixin:

@mixin responsive-border {     
    @media screen and (max-width: $mobile_threshold){
        background-color: $mobile-bg-color;
        border: $mobile-border;
    }

    @media screen and (min-width: $mobile_threshold + $threshold_step){
        background-color: $desktop-bg-color;
        border: $desktop-border;
    }
}

然后这样称呼:

div {
    margin: 50px;
    @include responsive-border; 
}

您可以对经常使用的任何规则执行相同的操作。 Mixins有助于保持代码干净。

答案 1 :(得分:0)

扩展jmargolisvt的答案 - 您还可以将属性的名称传递给mixin,并让它解决这个问题。

例如。

@mixin responsive-bg-color ($prop){
    @media screen and (max-width: $mobile_threshold){       
        #{$prop} : #ddddff;
    }

    @media screen and (min-width: $mobile_threshold + $threshold_step){
        #{$prop} : #ffffdd;
    }
}

@mixin responsive-margin-value($prop) {
    @media screen and (max-width: $mobile_threshold){       
        #{$prop} : 2px
    }

    @media screen and (min-width: $mobile_threshold + $threshold_step){
        #{$prop} : 20px
    }
}


div {
    margin: 50px; 

    border: solid 2px;  

    @include responsive-bg-color ("background-color");
    @include responsive-margin-value("padding-top");
}

p {
    @include responsive-margin-value("padding-bottom");

    background-color: #ddeedd;
}

这有点受限,因为您无法使用速记css,但它有效。