Search code examples
sveltedarkmode

CSS Not Changing Svelte + Chota


I have been learning Svelte for the past couple days and now I am trying to use it in combination with Chota. I am following the Chota docs instructions for dark mode but it won't change. In addition, if I add my own CSS it wont update. Here is my App.svelte:

<svelte:head>
    <link rel="stylesheet" href="https://unpkg.com/chota@latest">
</svelte:head>

<script>

    console.log("Checking!");

    if (window.matchMedia &&
            window.matchMedia('(prefers-color-scheme: dark)').matches) {
        document.body.classList.add('dark');
        console.log("Dark!");
    }

    export let name;

    function handleClick() {
        alert("Hello " + name)

    }
</script>

<nav class="nav">
  <div class="nav-left">
    <a class="brand" href="#">{name}</a>
    <div class="tabs">
      <a>Link 1</a>
      <a class="active">Link 2</a>
    </div>
  </div>
  <div class="nav-right">
    <a class="button outline" on:click={handleClick}>Button</a>
  </div>
</nav>

<style>
    body.dark {
        /* The background-color doesn't change anything, and neither does the other css. */
         background-color: red !important;
        --bg-color: #000;
        --bg-secondary-color: #131316;
        --font-color: #f5f5f5;
        --color-grey: #ccc;
        --color-darkGrey: #777;
    }
</style>

I have made sure that the code that adds the class is executing, and it is. I have added !important to the CSS yet it doesn't change anything.

EDIT:

I have been doing some more CSS testing and it seems that the :root selector works fine with variables (haven't tested with non-variables), but the body.dark selector doesn't even compile into the bundle.css file.


Solution

  • You should get an Unused CSS selector "body.dark" warning.

    That's because by default all css inside the <style> tag is scoped to the html inside the component.

    You are able to use selectors that style elements outside the by using:

    :global(body.dark) {
      background-color: red;
      ...
    

    or if all selectors in the style tag should be global use

    <style global>
      body.dark {
        background-color: red;
        ...
    

    https://svelte.dev/docs#component-format-style