Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to overwrite an SCSS variable based on screen width?

I have a varaible:

$font-color: red;

How do I overwrite its value on smaller screens?

This did not work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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.

>Solution :

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;
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading