Svelte is a front-end framework for web development, you can find more about it here. This post is about using CSS in Svelte.

CSS in Svelte Components

CSS styles specified in Svelte components are scoped to the component itself, meaning they don’t affect anything outside the component. Svelte compiler achieves this by making appropriate changes to the CSS and HTML.

It also bundles and minifies CSS from all the components into a single CSS file called ‘bundle.css’. Moreover, any unused styles are purged with along with compiler warnings.

Sharing styles from components

We can use ‘global’ keyword to avoid the styles being scoped to the components.

Here is a style for H1 tag.

h1 {
   color: #ff3e00;
   text-transform: uppercase;

We can make it global like this:

:global(h1) {
   color: #ff3e00;
   text-transform: uppercase;

Sharing styles using CSS file

Common styles can be specified in a CSS file and referenced in ‘index.html’. These styles can be used in any of the components. This is how we can include a CSS library in the project.

Pre and Post processing

Svelte has good support for pre and post-processing CSS. Mainly it is achieved through PostCSS plugin for Rollup. We can enable SASS or any required CSS feature by using PostCSS plugins.

While Svelte purges any unused CSS from components, we can use PurgeCSS plugin for PostCSS to do the same for global CSS. To make PurgeCSS understand Svelte syntax, we will have to use a custom extractor. Here is one for Svelte:

There is also a plugin to bundle imported CSS: Here is a quick guide on how to use it.


The Zen of Just Writing CSS By Rich Harris

Hi, I’m Umar

Leave a Reply

Your email address will not be published. Required fields are marked *