DEV Community 👩‍💻👨‍💻

Discussion on: Theming in Svelte with CSS Variables

josef profile image
Josef Aidt Author

Hi Isaac! Thanks for the feedback I really appreciate it. Disclaimer, this was the first time I built a theming solution from scratch like this and I wouldn't go as far to say what I've done is the best practice. To provide an explanation for your thoughts:

  1. Typically we see CSS variables set on :root, so that is my way to provide it to the entire document allowing elements like HTML and Body to access and apply these colors. In your example we see the colors start with the content, so only the content gets styled.

[ThemeContext] is wrapping the app anyway so they will be accessible to the entire app and would override any external values for the app

This is very true, and could definitely be done that way, however as noted above I was aiming to provide the colors to HTML and Body as well.

2. I didn't have time to try it out yet but... since the only thing that matters (for the appearance of the page) is the css variables, I wonder whether this could work without using context at all. The ThemeContext component would subscribe to a selected-theme store variable (which the toggle button can write to) and reactively set the css variables. Probably there is something I am missing here... can you shed some light pls?

That is also true, I chose context to provide a single import for both the consumption and dispatching updates, which in this example was provided by a pre-made function, toggle. Since the store is still provided with the context I suppose the toggle function can be re-rolled as well. When thinking of growth I tried this pattern to cut down on the multiple stores that may be imported into a single component, this way we can access with just getContext. To reinforce your thought, though, it can absolutely be done that way.

isaachagoel profile image
Isaac Hagoel

Thanks for the detailed reply. Makes sense!