Svelte: HTML expression does not apply all CSS styles

Created on 7 Jun 2019  路  2Comments  路  Source: sveltejs/svelte

When having code injected into a component via {@html expression}, the rendered HTML does not apply all of the component's CSS styles. In this example, only the first is properly styled:

<style>
    a { color: red; }
</style>

<script>
    let messageHTML = 'Here is an HTML expression without a styled <a href="/">link</a> :('
</script>

<div class="htmlText">
    Here is a normal styled <a href="/">link</a>
</div>
<div class="htmlText">
    {@html messageHTML}
</div>

Live reproduction: https://svelte.dev/repl/c1976e67d38d453dae297e90663c9ece?version=3.4.4

Most helpful comment

I think a note about that here https://svelte.dev/docs#html might be helpful. I struggled with this for a moment.

All 2 comments

This is expected. Svelte can only scope styles that it can statically analyze at compile time. If you need certain styles to be unscoped, you can wrap parts of the selector in :global( ).

A style like div.htmlText :global(a) { color: red; } would scope the div.htmlText part of the selector to this component, but would match _any_ a inside that, regardless of whether it's something Svelte can see while compiling.

I think a note about that here https://svelte.dev/docs#html might be helpful. I struggled with this for a moment.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

st-schneider picture st-schneider  路  3Comments

thoughtspile picture thoughtspile  路  3Comments

1u0n picture 1u0n  路  3Comments

davidcallanan picture davidcallanan  路  3Comments

noypiscripter picture noypiscripter  路  3Comments