Reputation: 473
I am trying to add some styling to an HTML tag rendered inside of the {@html...}
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
Upvotes: 20
Views: 6102
Reputation: 29585
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
Upvotes: 41
Reputation: 842
It could be a bug (but it seems difficult for Svelte to know what could be there in that string).
As (an ugly) workaround, you may choose to specify required style inlined. For example,
<script>
let string = `<h1 style="color:blue;">what</h1>`;
</script>
EDIT: And Svelte creator has answered the official way is using :global
.
Upvotes: 0