0

I have a simple SASS code that may be working like when the user has on his device set preferred color scheme dark the parameters from %dark-theme will extend to <body> and also when the user has preferred color scheme light the %light-theme will be extended instead of %dark-theme to <body>.

The same parameters which are used in %dark-theme and %light-theme may be extended on <body> when <body> have set id to #switched-dark-mode or #switched-light-mode. This IDs are set by Javascript after user switch the theme color.

Is there any solution to how I can make my SCSS clear and parameters which are used in @extends write only one time and use them in media query and also in ID selector?

MY CODE:

%dark-theme {
    background: black;
    color: white;
}

%light-theme {
    background: white;
    color: black;
}

@media (prefers-color-scheme: dark) {
    body {
        @extend %dark-theme;
    }
}

@media (prefers-color-scheme: light) {
    body {
        @extend %light-theme;
    }
}

body {
    &#switched-dark-mode {
        @extend %dark-theme;
    }

    &#switched-light-mode {
        @extend %light-theme;
    }
}
Matúš Rebroš
  • 115
  • 1
  • 9

1 Answers1

0

Unfortunately you cannot specify multiple selectors when using @media queries in SCSS (or at least to my knowledge). What you have already is a good solution.

One workaround you could try would be to use the "prefers-color-scheme" query in JavaScript when you load the page to apply the appropriate ID on the body element, which would allow you to remove the two @media queries from your SCSS code.

That means you could just move the styles defined in %dark-theme and %light-theme into the appropriate body selector.

Check out this post for reference and other solutions:

How to override css prefers-color-scheme setting

KingsthwaiteJ
  • 464
  • 4
  • 10