Reputation: 59
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>
?
Upvotes: 1
Views: 949
Reputation: 3446
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.
Upvotes: 0
Reputation: 76564
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.
Upvotes: 0
Reputation: 2048
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.
Upvotes: 4