aclowkay
aclowkay

Reputation: 3897

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)

Upvotes: 7

Views: 2357

Answers (3)

Darren Bounds
Darren Bounds

Reputation: 1

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>

Upvotes: 0

user1825508
user1825508

Reputation: 1

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.

Upvotes: 0

Stephane Vanraes
Stephane Vanraes

Reputation: 16451

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.

Upvotes: 10

Related Questions