Home > Back-end >  Styling the body element in svelte
Styling the body element in svelte

Time:04-06

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?

CodePudding user response:

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.

  • Related