Karl Põdra
Karl Põdra

Reputation: 243

Svelte: Adding a class to a div doesn't add the classes CSS to div

We are having a problem where on click is adding a class to a div but the classes CSS doesn't get add to the div. It just adds the class.

<script>
    function handleClick() {
        document.getElementById('text').classList.add('blueText')
    }
</script>
<style>
    .blueText{
        color:blue;
    }
</style>
<button on:click={handleClick}>
    Click me
</button>
<div id="text">
        Text
</div>

Created a REPL to see it as well. Any explanations or solutions appreciated

https://svelte.dev/repl/85554a5f15134a5694c36fc4f4782029?version=3.23.2

Upvotes: 11

Views: 9835

Answers (1)

rixo
rixo

Reputation: 25001

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>

Upvotes: 22

Related Questions