skip to Main Content

I have a varaible:

$font-color: red;

How do I overwrite its value on smaller screens?

This did not work:

$font-color: red;

@media (max-width: 500px){
    $font-color: blue;
}

Also, this is in a global variables file. I want that so whenever on a smaller screen the overwriting of the variable will affect everything in every other file.

2

Answers


  1. In SCSS, variables are set at compile time and cannot be changed dynamically during runtime. Therefore, if you want to change the value of a variable based on a media query, you need to structure your code differently.

    One way to achieve what you want is to use the variable in a CSS rule inside the media query, rather than trying to redefine the variable itself. Here’s an example:

    $font-color: red;
    
    body {
      color: $font-color;
    
      @media (max-width: 500px) {
        color: blue;
      }
    }
    

    You might consider using CSS variables, they can be modified at runtime using media queries.

    Here’s an example:

    :root {
      --font-color: red;
    }
    
    body {
      color: var(--font-color);
    
      @media (max-width: 500px) {
        --font-color: blue;
      }
    }
    
    Login or Signup to reply.
  2. For the sake of completeness, using SASS variables dynamically

    :root {
      --font-color: orange;
      @media (max-width: 500px) {
        --font-color: green;
      }
    }
    $font-color: var(--font-color);
    body {
      font-family: system-ui, -apple-system, sans-serif;
      background-color: $font-color !important;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search