OiO.lk Blog HTML Set `body` `background-color` programmatically in Svelte?
HTML

Set `body` `background-color` programmatically in Svelte?


I’m making a site using Svelte and SvelteKit, and I’d like to use a predefined array of colors for styling in a normalized way– if I change one of the values later, everywhere that styles using that value will be updated later.

// palette.js

export const grays = [
  'hsl(240 3.7% 10.6%)',
  'hsl(240 13% 18%)',
  ...
];
// routes/+page.svelte

<script>
  import { grays } from '$lib/palette.js';
</script>

<div style="background-color: {grays[0]};">
  <i>stuff</i>
</div>

My problem is I can’t figure out which is the best way to apply one of my colors to <body>.

Setting CSS values in a <style> tag like this:

<style>
  :global(body) {
    background-color: {grays[0]};
  }
</style>

is not valid syntax for Svelte (and using :global rules generally seems to be unidiomatic).

My current options (that I can think of) seem to be:

  1. Set the document.body.style.backgroundColor in a <script>— might cause flickering?
  2. Don’t style <body> at all, style a big <div> with a custom CSS property that covers everything (as shown in the Svlte tutorial)– probably my best option but seems a bit ugly / smelly / boilerplatey to do all the var(...) and style="--customvar={grays[0]};.

What should I do? Am I overthinking this?



You need to sign in to view this answers

Exit mobile version