Home > Mobile >  Angular dark theme and root css variables
Angular dark theme and root css variables

Time:09-10

On my site, I am adding the possibility to switch between a dark mode and a light mode. And so I have a service that allows me to make this switch without too many problems on the css side. Basically, I declared css variables at the :root level and I redeclared these same variables in :root.dark-theme.

When I click on a button I add or remove the dark-theme class.

if (this.isDark) {
      this.renderer.addClass(this.document.body, 'dark-theme');
    } else {
      this.renderer.removeClass(this.document.body, 'dark-theme');
    }

My problem is that I am trying to retrieve the values ​​of some variables directly in my component.

I tried this piece of code to retrieve the value of a particular variable.

getComputedStyle(
        document.documentElement
      ).getPropertyValue('--border-color');

I manage to retrieve the one in :root but when I switch and add dark-theme, it always retrieves the value in :root and not in :root.dark-theme.

How can I manage to retrieve the values in dark-theme as well?

CodePudding user response:

change the element parameter of getComputedStyle to document.body

getComputedStyle(document.body).getPropertyValue('--border-color')
  • Related