Search code examples
svelte

Use svelte css class in @html


I have an api that returns html with classes, I want to know how I can use svelte style definition for those.

App.Svelte

<script>
    let string = `<span class="status">ok</span>`;
</script>

<p>{@html string}</p>

<style>
    .status {
        color: red
    }
</style>
... 

{@html marked}

Returns Unused CSS selector (8:1)


Solution

  • Svelte will remove all CSS it cannot find in the markup, which is why it's removing the status class in your sample. There is however a way to tell Svelte to leave these classes alone and that's by simply declaring them global:

    :global(.status) { }

    Beware that this would apply these styles to ALL .status classes in your app, to still have some scoping you could make this a child selector somehow

    
    <style>
     .wrapper > :global(.status) {
     }
    </style>
    
    <div class="wrapper">
      {@html marked}
    </div>
    

    This way it will only be applied to status classes inside of wrapper.