Felkru
Felkru

Reputation: 444

Styling the body element in svelte

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:

Upvotes: 20

Views: 17056

Answers (2)

Felkru
Felkru

Reputation: 444

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">

Upvotes: 0

cSharp
cSharp

Reputation: 3159

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.

Upvotes: 31

Related Questions