15

My goal is to make a darkmode for my web app. To get my setup enter npm init vite and pick svelte as a framwork. Then follow the command line instructions. Go to src > App.svelte:

Try the following:

body {
    background: black;
}

You will get the following warning by the svelte extension in vs-code:

Unused CSS selector "body"

Image of my css and the warning

To check if this error is related to the browser I manually set the property in chrome dev tools and the expected result was achieved.

Image of the same css working in dev tools

Because of this I have the following questions:

  • Why doesn't svelte allow styling of the body in this way?
  • How can you style the body tag in svelte?
  • How would darkmode be implemented?
rioV8
  • 24,506
  • 3
  • 32
  • 49
Felkru
  • 310
  • 2
  • 12

2 Answers2

23

Why doesn't svelte allow styling of the body in this way?

Because svelte styles are scoped by default. You have to explicitly tell svelte that you want to apply a style globally.

How can you style the body tag in svelte?

You want to use the css selector :global(body) instead of body.

How would darkmode be implemented?

In the similar way you style :global(body), using the :global(body.dark-mode) selector. Here is an example.

cSharp
  • 2,884
  • 1
  • 6
  • 23
0

You can achieve what I tried to do by adding a global.css file to your project and importing it to your file like this:

<script>
  import "./global.css";
</script>

If you really want it to be global you can also link it in your index.html in the root of your project like this:

<link rel="stylesheet" href="styles.css">
Felkru
  • 310
  • 2
  • 12