Reputation: 7338
I noticed that svelte will purge my css automatically, all "unused css selector" will get removed.
For example:
<p class="blue">This is a paragraph.</p>
<style>
.red{
color: red;
}
.blue{
color: blue;
}
</style>
The style for class 'red' will be removed. How can I keep the '.blue' selector? I want to use it later at some point.
Upvotes: 21
Views: 10311
Reputation: 1234
If you're using Sveltekit, you can create a app.css (or scss) file and import it into your main +layout.svelte
file.
import '../app.scss';
If you're not using sveltekit, you can edit the global.css
file found in public/global.css
This guide explains the Sveltekit version in more detail
Upvotes: 3
Reputation: 2401
I found a solution that doesn't use global styles. You can 'outsmart' the unused rule detector by using :is()
.
<style>
:is(.red) {
color: red;
}
.blue {
color: blue;
}
</style>
compiles to
.svelte-1xo9h64:is(.red) { color:red }
.blue.svelte-1xo9h64 { color:blue }
Please note that :is()
is not supported in all browsers.
https://caniuse.com/css-matches-pseudo
Upvotes: 9
Reputation: 3360
I tried :global()
, <style global>
and @import
but nothing worked. My case was something like this:
<ul>
{#each items as item}
<li class="method–{item.method}">{item.text}</li>
{/each}
</ul>
I finally found a solution that worked:
<li class="{'method-' + item.method}">
Makes no difference in the output but somehow doesn't trigger the CSS purging. Really annoying to have to deal with awkward tooling bugs.
Upvotes: 1
Reputation: 2190
You can also use global in the style tag, if you have svelte-preprocess
installed (link):
<style global>
.red{
color: red;
}
.blue{
color: blue;
}
</style>
Upvotes: 13
Reputation: 5645
You probably want to wrap the selector in :global(...)
, like
:global(.red) {
color: red;
}
This forces Svelte to keep the class around, and also makes it so the selector isn't scoped to that single component. This is usually what you want when Svelte is removing selectors that you want to keep.
Upvotes: 16