3

I have a quick question, why does this work in my app/javascript/stylesheets/application.scss

@import 'materialize-css/sass/components/_color-variables';

$primary-color: color('blue', 'lighten-2') !default;
$secondary-color: color('yellow', 'base') !default;

@import 'materialize-css/sass/materialize';

But this doesn't

@import 'materialize-css/sass/components/_color-variables';

@if (prefers-color-scheme: dark) == 'dark' {
    $primary-color: color('blue', 'lighten-2') !default;
    $secondary-color: color('yellow', 'base') !default;
}

@import 'materialize-css/sass/materialize';

What I am trying to do is override Materialize CSS's defaults if the user has a different system setting for his/her color mode in their operating system (prefers-color-scheme).

doer123456789
  • 369
  • 1
  • 7
  • 22

1 Answers1

1

Answer: variable without flow control (your code example 1) can be set at css compilation because it is defined. Variable with flow control (your code example 2) can not be set at css compilation because (prefers-color-scheme: dark) is undefined.

Bare CSS file does not support flow control logic at run time. Off-topic: but some people say it is Turing-complete.

Preprocessor SASS/SCSS supports flow control logic to ease maintenance. Flow control is evaluated at compile time, but not at run time. In other words, at compile time (prefers-color-scheme: dark) can not be evaluated. When server has sent css file to client, client's browser can execute window.matchMedia('(prefers-color-scheme: dark)') and pick-up correct style according to mode. Compiled CSS file should look like this:

@media (prefers-color-scheme: light) {
  div {
    background-color: #0F0;
    color: #F00;
  }
}

@media (prefers-color-scheme: dark) {
  div {
    background-color: #FF0;
    color: #00F;
  }
}
zswqa
  • 826
  • 5
  • 15