Loading a set of css variables in Sveltekit from a file

193 views Asked by At

I'm building an app in SvelteKit and Tauri. I'd like to be able to give users the option to define themes through .css files (or whatever works). My app currently handles colours through a set of variables defined in +layout.svelte like this:

:root {
        --w500: #f4f3f2;
        --bg400: #dbd6d0;
        --bg500: #F3EEE7;
        --bg600: #f4f0e9;
        --g100: #121212;
}

Is there any way I could do something similar (maintaining some kind of set of color variables for use in CSS) while loading styles dynamically from a file?

1

There are 1 answers

3
brunnerh On BEST ANSWER

You could add <link> or <style> elements using either <svelte:head> or onMount. If you use onMount the element should be removed again in the cleanup function.

Just using a <style> and setting its contents is probably easier, then you do not have to worry about serving dynamic files.

I have found that <svelte:head> can lead to inconsistent results as elements can be added earlier or later depending on whether a route adding the elements was server or client-rendered. (For CSS, later styles overwrite rules with identical selectors.)