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

1

11

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

Throttle answered 2/7, 2020 at 14:16 Comment(1)
You are referring to a class, but have given the <div> only and "id". Try adding a class to the <div>Talia
M
22

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>
Mencius answered 2/7, 2020 at 15:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.