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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With