Search code examples
javascriptcssstorybookdarkmode

css darkmode variables being ignored by storybook


I have the following css which is loaded into my project:

// Default theme (light mode)
:root {
  /* Typography */
  --col-body-text: #0b0c0c;
  --col-body-text-light: #505a5f;
}

// Dark mode theme
:root.dark {
  /* Typography */
  --col-body-text: #c5c5c5;
  --col-body-text-light: #f8f8f8;
}

In my actual app this works as expected, however, in storybook, it ignores the dark mode variables.

I have updated my preview.js file to add '.dark' to the `HTML element when dark mode is selected - which works as expected - indeed all of the other dark mode specific code in the components works fine. It's only those variables that are being ignored.

Is there an issue with using :root in storybook that I'm not aware of or something?

if it helps, here is the code that adds the class to the HTML element:


// get an instance to the communication channel for the manager and preview
const channel = addons.getChannel()

// switch body class for story along with interface theme
channel.on('DARK_MODE', isDark => {
  if (isDark) {
    document.documentElement.classList.add('dark')
  } else {
    document.documentElement.classList.remove('dark')
  }
})

Solution

  • If you place such stylesheet in the HTML page (e.g. in the <head>), the :root selector refers to <html> (https://developer.mozilla.org/en-US/docs/Web/CSS/:root). If you want to use the :root selector with a class, you need to set the class on the <html> element (rather than on <body> suggested in another answer), so document.documentElement.classList.add('dark') is correct.

    There is a playground which uses the Storybook syntax and features where I created a working example for you: https://webcomponents.dev/edit/p8TI3583HotsFNWjBMd8/src/index.stories.js

    Not sure if your Storybook is configured in another manner, maybe your stylesheet is not really added or gets overwritten somewhere later. Please also verify if you use the CSS Custom Properties (aka CSS vars) correctly, I hope the working demo helps there too.