Svelte compiler removes unused CSS rules, and it only see classes that are actually used in the component's markup.
It has to do this to be able to scope your component's CSS, because scoping works by adding a unique generated class to all the component's elements that have a matching (scoped) CSS rule.
In your case, the compiler doesn't see the blueText
class in the markup, as indicated by the "Unused CSS selector" warning.
Use Svelte conditional class to have a conditional (and scoped) class that the compiler is aware of:
<script>
let isBlue = false
function handleClick() {
isBlue = !isBlue
}
</script>
<style>
.blueText {
color: blue;
}
</style>
<button on:click={handleClick}>
Click me
</button>
<div class:blueText={isBlue}>
Text
</div>
Or, with shortcut syntax:
<script>
let blueText = false
function handleClick() {
blueText = !blueText
}
</script>
<style>
.blueText {
color: blue;
}
</style>
<button on:click={handleClick}>
Click me
</button>
<div class:blueText>
Text
</div>
If you don't want your conditional class to be scoped, you can simply make it :global
-- Svelte compiler never trims global rules, it doesn't need to.
<script>
function handleClick() {
document.getElementById('text').classList.add('blueText')
}
</script>
<style>
:global(.blueText) {
color: blue;
}
</style>
<button on:click={handleClick}>
Click me
</button>
<div id="text">
Text
</div>