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
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