WoJ
WoJ

Reputation: 29987

Is it possible to assign a class to :root?

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

Answers (3)

FZs
FZs

Reputation: 18619

It can be done easily with JS.

  1. Select the element:

    const root = document.querySelector(':root')
    
  2. 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

WoJ
WoJ

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

Rickard Elim&#228;&#228;
Rickard Elim&#228;&#228;

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

Related Questions