How To Use Global Styles In SvelteKit

Table of Contents

app.html

You can include your global styles inside app.html in SvelteKit but then you can’t take advantage of HMR (hot module replacement) since SvelteKit has no idea the file got updated.

src/app.html
<!-- ... -->
  <head>
    <style>
      h1 {
        color: aqua;
      }
    </style>
  </head>
<!-- ... -->

+layout.svelte

Instead use a +layout.svelte file and import your styles.

src/app.css
h1 {
  color: aqua;
}
routes/+layout.svelte
<script>
  import '../app.css'
</script>

<slot />

The base layout wraps the entire SvelteKit app.

:global

Svelte ignores styles that aren’t part of your template which sucks when you don’t have control over the markup from a CMS (content management system), or the markup is inside another component.

In that case you can use :global.

+page.svelte
<script>
  export let data
</script>

<div class="prose">
  {@html data.content}
</div>

<style>
  :global(.prose h1) {
    color: aqua;
  }
</style>

You can scope .prose to the component if you want.

+page.svelte
<!-- ... -->

<style>
  .prose :global(h1) {
    color: aqua;
  }
</style>

SvelteKit by default comes with the svelte-preprocess preprocessor where you can use the global attribute on the <style> tag to avoid typing :global everywhere if you’re not using SASS.

+page.svelte
<!-- ... -->

<style global>
  .prose h1 {
    color: aqua;
  }
</style>
Found a mistake?

Every post is a Markdown file so contributing is simple as following the link below and pressing the pencil icon inside GitHub to edit it.

Edit on GitHub
Subscribe For Updates