1

I am implementing a dark mode on my site, and trying to do it in the cleanest way possible (no boiler plate code).

So I want to make .darkmode class in CSS, define styles with it, and when the user enables darkmode, javascript simply adds the darkmode class to the <body>.

How could I do something like this with CSS?

.darkmode {
    .content{
        background-color: black;
    }
    input{
        background-color: black;
    }
}

So my questions is, how can I make CSS change different elements on the page when adding this class to the <body>?

1
  • You can't do this syntactic sugar in CSS but you can in Sass or Less. The only way to do it in vanilla CSS would be .darkmode .content {...} .darkmode input {...} Commented Oct 4, 2017 at 20:02

3 Answers 3

4

The code that you posted would be valid SCSS/LESS. But in plain css you can simply do that by using

.darkmode .content { /* CSS */ }
.darkmode input { /* CSS */ }

So yes, you always have to specify the .darkmode in front of every selector.

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

1 Comment

Awesome! Thanks for solution.
0

Let's suppose you have a selector, like

.mydiv .myanchor

You can override/add attributes using

body.darkmode .mydiv .myanchor

is much more specific and therefore the rules will override the default rules.

Comments

0

To achieve that in normal CSS you would have to use the CSS child selector;

body.darkmode .content {
  /* Put styles here */
}
body.darkmode input {
  /* Put styles here */
}

Basically the logic there says: "get the body element with the class darkmode and find it's child .content/input"

With CSS selectors, having two element selectors seporated by a space finds all of the second elements inside the first elements; div p would find all of the <p> tags inside all <div> tags.

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.