Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styling a {@html...} tag of a Svelte component by ising the in-component <style> tag (Unused CSS selector)

I am trying to add some styling to an HTML tag rendered inside of the {@hml...} tag of a Svelte component, but it appears that it only inherits the parent's styling (the container of the {@html...} tag). Moreover, the Unused CSS selector error pops up displaying that my styling selector for that specific HTML tag inside of the Svelte {@html...} tag merely doesn't work. Is Svelte built that way and is there a method for styling tags that are rendered inside of the Svelte {@html...} tag?

I've tried steps provided in the official Svelte tutorial, but they don't clearly show how to do it.

<style>
    p{
        color: red;
    }
    h1{
        color: blue;
    }
</style>

<script>
    let string = "<h1>what</h1>";   
</script>

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

I want the h1 tag to be blue, not inherit the red color from the p tag

like image 325
Marvelous Walrus Avatar asked Jun 15 '19 05:06

Marvelous Walrus


People also ask

How do I use CSS in Svelte?

In Svelte, you can write CSS in a stylesheet like you normally would on a typical project. You can also use CSS-in-JS solutions, like styled-components and Emotion, if you'd like. It's become increasingly common to divide code into components, rather than by file type.

Is Svelte CSS scoped?

With Svelte you are not forced to be using scoped CSS styling. In fact, you can be using the traditional CSS files like you used to, or you can be using the :global selector inside your <style> tags to write CSS that will target elements globally in your project.


1 Answers

You need to use the :global(...) modifier. If you do this...

:global(h1) { color: blue }

...it will apply to all <h1> elements on the page — both the one inside the {@html ...} tag and any that exist in other components.

To restrict it to elements inside this component, put the selector inside a local one:

p :global(h1) { color: blue }

That selector will only apply to <h1> elements inside <p> elements belonging to this component. Here's a demo

like image 97
Rich Harris Avatar answered Sep 22 '22 15:09

Rich Harris