Reputation: 29987
As I am thinking about solutions to another problem of mine, I am trying to understand to which extend CSS elements can inherit from other elements. Specifically, having the following definition
.dark {
background-color: black;
}
.light {
background-color: white
}
is it possible to programmatically assign (with JS, probably) one of these classes to the :root
element?
Upvotes: 1
Views: 2510
Reputation: 18619
It can be done easily with JS.
Select the element:
const root = document.querySelector(':root')
Assign the class to it:
root.classList.add('light')
All together:
const root = document.querySelector(':root')
root.classList.add('light')
Or, instead of having two classes, it might be better to have a :not()
selector:
:root:not(.dark){
background-color: white;
}
:root.dark{
background-color: black;
}
Upvotes: 4
Reputation: 29987
In HTML, :root
is equivalent to <html>
(doc):
In HTML, :root represents the element and is identical to the selector html, except that its specificity is higher.
A possible solution would be to apply the class to <html>
:
document.getElementsByTagName("html")[0].classList.add('dark')
.dark {
background-color: red;
}
<html>
hello
</html>
Upvotes: 0
Reputation: 7591
I would use (and have used) CSS variables for this.
:root {
--background-color: black;
}
.background {
background-color: var(--background-color);
}
Then change the CSS variable with javascript.
Upvotes: 0