Use svelte css class in @html
Asked Answered
A

3

7

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)

Aventurine answered 18/3, 2020 at 7:0 Comment(0)
E
10

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.

Earthman answered 18/3, 2020 at 7:10 Comment(0)
J
0

I was trying to do this with the h2 tag, since I am integrating tincyMCE in a svelte app that is using 'flowbite-svelte'. What worked for me was:


    :global(.content h2) {
        font-size: 1.5em;
      }

Where 'content' was my div class.

Josiejosler answered 25/7, 2023 at 8:10 Comment(0)
B
0

There is one alternative which you may find more appealing than :global(), depending on your situation.

You can choose to import CSS and have it only flow down to child pages within your project.

For example if you have a structure like this:

routes/app
       +layout.svelte
       /subpages
      /portal
       +layout.svelte
       /subpages
      /marketing
       +layout.svelte
       /subpages

You can import CSS into the section of the layout in any one of the above layouts and only have it apply to all the child pages beneath it.

<script>
   import "../styles/marketing.styl"
</script>
Bargello answered 7/7 at 13:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.