DEV Community

Nathan
Nathan

Posted on • Originally published at natclark.com

Writing Global Styles in Svelte

In Svelte, styles are scoped by default to prevent collisions.

This is great and all, but there are plenty of cases where it is practical to write global styles.

Here is an example of making a <p> element globally white when it has the .dark-mode selector:

<style>
    p {
        color: black;
    }
    :global(p.dark-mode) {
        color: white;
    }
</style>
Enter fullscreen mode Exit fullscreen mode

If you've enabled SCSS within your Svelte components, you can include multiple child selectors and declaration blocks under one :global selector like this:

<!-- If SCSS is enabled, but not default, then you'll need to add `lang="scss"`: -->
<style lang="scss">
    body {
        background-color: white;
    }
    p {
        color: black;
    }
    :global {
        body.dark-mode {
            background-color: black;
        }
        p.dark-mode {
            color: white;
        }
    }
</style>
Enter fullscreen mode Exit fullscreen mode

And if all of your component's styles need to be global, then you can also just add the global attribute to your <style> tag:

<style global>
    body.dark-mode {
        background-color: black;
    }
    p.dark-mode {
        color: white;
    }
</style>
Enter fullscreen mode Exit fullscreen mode

I would suggest avoiding using global styles when they could be scoped instead, just to prevent potential future collisions.

However, there's plenty of cases where it's more practical to go global!

Conclusion

Svelte can be a really fun and productive framework once you get the hang of it, but it can be frustrating at times while you're still getting acclimated to some of these unique features.

Anyway, thanks for reading!

Top comments (0)