在媒体查询中重新定义sass变量

时间:2017-06-16 11:04:24

标签: variables sass

说这个常见用例:

h2{ // logo
  $width: 146px;
  $height: 22px;
  @include size($width, $height); // previously defined mixin for simple size assignment

  a{
    @include size($width, $height);
  }

  @include mq($medium-aux-up){
    $width: 180px;
    $height: 28px;
    @include size($width, $height);

    a{
      @include size($width, $height);
    }
  }

  @include mq($large-up){
    $width: 220px;
    $height: 34px;
    @include size($width, $height);

    a{
      @include size($width, $height);
    }
  }
}

是否有办法仅通过覆盖$ width和$ height值来更改媒体查询的大小?像这样(假的):

h2{ // logo
  $width: 146px;
  $height: 22px;
  @include size($width, $height);

  a{
    @include size($width, $height);
  }

  @include mq($medium-aux-up){
    $width: 180px;
    $height: 28px;
  }

  @include mq($large-up){
    $width: 220px;
    $height: 34px;
  }
}

2 个答案:

答案 0 :(得分:1)

SCSS:

$medium-aux-up: "other";
$large-up: "another";

@mixin mq($size) {
  @media (#{$size}) {
    @content;
  }
}

@mixin size($width, $height) {
  width:  $width;
  height: $height;
}

h2 {
  &, a {
    @include size(146px, 22px);
  }

  @include mq($medium-aux-up){
    &, a {
      @include size(180px, 28px);
    }
  }

  @include mq($large-up) {
    &, a {
      @include size(220px, 34px);
    }
  }
}

CSS已优化:

h2, h2 a {
  width: 146px;
  height: 22px;
}
@media (other) {
  h2, h2 a {
    width: 180px;
    height: 28px;
  }
}
@media (another) {
  h2, h2 a {
    width: 220px;
    height: 34px;
  }
}

DEMO

答案 1 :(得分:0)

例如,您可以使用函数根据媒体查询计算更长的时间长度。您也可以调整此数学,例如添加n值或任何您想要的值。

$width:100px;
$height:100px;


@function lengthMedia($media){
  $base: 1;
  @if($media == 'xs'){
    $base: 2;
  }
  @else if($media == 'md'){
    $base: 3;
  }

  @return $base * $width;
}

.foo{
  width: lengthMedia('xs');

}

@media (min-width:500){
  .foo{
    width: lengthMedia('md');
  }
}