How To Use Global Styles In SvelteKit
Published Nov 24, 2022
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.
<!-- ... -->
<head>
<style>
h1 {
color: aqua;
}
</style>
</head>
<!-- ... -->
+layout.svelte
Instead use a +layout.svelte
file and import your styles.
h1 {
color: aqua;
}
<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
.
<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.
<!-- ... -->
<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.
<!-- ... -->
<style global>
.prose h1 {
color: aqua;
}
</style>