5

Short question

Is it possible to do something like @media (prefers-color-scheme: dark), body.dark? So the possibility to combine css selectors with css queries.

Longer question with background

(Maybe there is another solution to this problem that I didn't think of)

I'm currently developing a web application which has a dark and a light theme.

I started switching it using @media (prefers-color-scheme: dark). However, many older phones unfortunately do not support this, so I decided to implement a way to change it by hand. Therefore I add the classes light or dark to the body depending of the user settings.

In my scss file I want to set variables depending on .light or .dark and if none of these classes are set it should depend on the media query with the default being .light.

My current approach looks like this:

// setting all the light-mode variables:
--header-color: white;

@media (prefers-color-scheme: dark) {
  body:not(.light) {
    --header-color: dark-grey;
  }
}

While this achieves the goal if the media query is set to dark it won't work otherwise since you're unable to "force" darkmode currently.

Of course I could add another section below this with body.dark{} but then I would need to copy every variable which are quite a lot.

So I was wondering if it's possible to do something like @media (prefers-color-scheme: dark), body.dark.

Or if there is any other option to have a block select the body if

  • it has the class light

or

  • if the preferred color scheme isn't dark and
  • the body does not have the class dark

and the other block select the body if

  • it has the class dark

or

  • if the preferred color scheme is dark.

But both being one block and not two so that I don't have to have every variable twice.

Thank you very much already.

1 Answer 1

1

After some time I stumbled upon a solution for my problem. Even though I never found a way to combine those selectors I was able to minimise code redundancy using sass mixins. Honestly I don't know why it took me so long to come up with this but I thought maybe I can help someone else with it.

@mixin light-colors() {
    --accent-blue: #586B7C;
    // ...
}

@mixin dark-colors() {
    --accent-blue: #232B30;
    // ...
}

:root {
    @include light-colors();
}

@media (prefers-color-scheme: dark) {
    :root:not(.light) {
        @include dark-colors();
    }
}

:root.dark {
    @include dark-colors();
}

This helps to structure the code as well as minimizing the code redundancy I previously had.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.