我可以更新媒体查询中的SASS变量吗?

时间:2016-11-22 10:41:17

标签: css sass

考虑以下SASS代码。我想确保如果屏幕高于1250px,则margin-top应为750px,然后应根据尺寸进行更改。但是,SASS不允许我更新字符串中的变量。

// Above 1250px
$pageTemplateMargin:750px;

// Below 1250px
@media screen and (max-width:1250px){
    $pageTemplateMargin:550px;
}

// Below 950px
@media screen and (max-width:950px){
    $pageTemplateMargin:450px;
}

@media screen and (max-width:850px){
    $pageTemplateMargin:150px;
}

@media screen and (max-width:750px){
    $pageTemplateMargin:250px;
}

// Render the correct code
.page-template {margin-top:$pageTemplateMargin}

是否有更好的方法,因为它不起作用且page-template停留在750px

由于

3 个答案:

答案 0 :(得分:5)

我同意接受的答案,在这种情况下使用maps会更好,但我想指出一些事情。

变量实际上可以在媒体查询中更新。问题是在块外定义的变量是全局变量,而块中定义的变量是局部变量。您可以使用!global 关键字让sass将块中的变量视为全局变量。

$pageTemplateMargin:750px;

@media screen and (max-width:1250px){
    $pageTemplateMargin: 550px !global;
}

.page-template {
  margin-top: $pageTemplateMargin //will use 550px instead of 750px
}

只是想澄清一下,尽管在这个用例中它是不合适的。

我还建议您使用loop作为代码,这将非常有用,尤其是如果您添加更多屏幕宽度和边距属性,这样您就不需要进一步编写更多媒体查询。

$breakpoints: (
  1200px: 10px,
  1000px: 15px,
  800px: 20px,
);

@each $width, $margin in $breakpoints {
  @media screen and (max-width: $width) {
    .element {
      margin-top: $margin;
    }
  }
}

希望这有帮助。

答案 1 :(得分:2)

不,你不能(在这种情况下,正如另一个答案所指出的那样)。

我建议使用mixins来处理此问题:

@mixin pageTemplateMargin($px) {
    margin-top: $px
}

@media screen and (max-width:1250px) {
    .element { @include pageTemplateMargin(10px);}
}
@media screen and (max-width:1000px) {
    .element { @include pageTemplateMargin(15px);}
}
@media screen and (max-width:800px) {
    .element { @include pageTemplateMargin(20px);}
}

还有一种通过sass对象进行映射的方法,例如:

$breakpoints: (
  1200: 10px,
  1000: 15px,
  800: 20px,
);

@media screen and (max-width:1200px) {
    .element { margin-top: map-get($breakpoints, 1200);}
}
@media screen and (max-width:1000px) {
    .element { margin-top: map-get($breakpoints, 1000);}
}
@media screen and (max-width:800px) {
    .element { margin-top: map-get($breakpoints, 800);}
}

这将允许您通过调整1变量来全局更改边距。

Working codepen example

答案 2 :(得分:0)

我已经尝试过了,然后解决了问题。它将根据给定的速率(基本大小/速率大小)自动计算所有媒体断点


$base-size: 16;
$rate-size-xl: 24;

    // set default size for all cases;
    :root {
      --size: #{$base-size};
    }

    // if it's smaller then LG it will set size rate to 16/16;
    // example: if size set to 14px, it will be 14px * 16 / 16 = 14px
    @include media-breakpoint-down(lg) {
      :root {
        --size: #{$base-size};
      }
    }

    // if it is bigger then XL it will set size rate to 24/16;
    // example: if size set to 14px, it will be 14px * 24 / 16 = 21px
    @include media-breakpoint-up(xl) {
      :root {
        --size: #{$rate-size-xl};
      }
    }

@function size($px) {
   @return calc(#{$px} / $base-size * var(--size));
}

div {
  font-size: size(14px);
  width: size(150px);
}