Search code examples
csssassmedia-queries

SASS variable with @media in css not working


variables.scss:

$large-screen: 1200px;
$screen-large: #{($large-screen - 1)};
$large-down: 'screen and (max-width: #{$screen-large})';
@debug $screen-large;

In another scss file:

@import '../../styles/variables.scss';
@media #{$large-down} {
    my styling…
}

Problem: It doesn’t apply the "My styling" part.
If I replace the @media line with @media only screen and (max-width: 1199px) { it does work.
Any idea what I am doing wrong?

Update: I discovered that $screen-large: #{($large-screen - 1)}; results in "1200px - 1" rather than "1199px". Is there a way in SASS to make it do the calculation instead of take it as a string?

I've tried $screen-large: calc($large-screen - 1); but it still returns that whole line as a string rather than do the calculation.


Solution

  • Found the solution:

    variables.scss:

    $large-screen: 1200px;
    $screen-large: ($large-screen - 1);  // Now it no longer interpolates to a string.
    $large-down: 'screen and (max-width: #{$screen-large})';
    

    In another scss file:

    @import '../../styles/variables.scss';
    @media #{$large-down} {
        my styling…
    }