TheBlackBenzKid TheBlackBenzKid - 15 days ago 9
Sass (Sass) Question

Can I update SASS variables in Media Queries?

Consider the following SASS code. I want to make sure that if the screen is above

1250px
then the
margin-top
should be
750px
and then it should change depending on size. However SASS does not allow me to update the variables inside the strings.

// 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}


Is there a better way for this, as it does not work and
page-template
stays at
750px
.

Thanks

Answer

No, you can't.

I'd suggest using mixins to work with this:

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

There's also a way of mapping through sass objects, such as:

$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);}
}

This would allow you to globally change the margin by adjusting 1 variable.

Working codepen example