Skip to content

Optionally embed styles in the DOM if the styles are in JS. #4039

Closed
@milkbump

Description

@milkbump

Is your feature request related to a problem? Please describe.
There is no way to control where Svelte embeds styles in JS that are not exported using the css: true compile option. Styles are currently embedded in the head tag, though it may not always be desirable. For example, if my Svelte component is used in a custom-element with a shadow dom, styles in the head are not applied due to encapsulation.

Secondly, if my element is rendered in an environment without a head tag, Svelte throws an error. For example, the Chrome PDF viewer is an embedded page that doesn't have a head tag. It's frustrating when embedding Svelte components in the PDF viewer through Chrome extensions. If I expect such environments, I should be able to choose where the styles go.

Describe the solution you'd like
The best solution I could come up with was using an option

<svelte:option css={true} />

Then when rendered will add the styles inline next to my component instead of the head:

<foregn-custom-element>
<div class="my-component svelte-123">my div</div>
<style>
     div.svelte-123 {
          color: red;
     }
</style>
</foreign-custom-element>

Describe alternative solutions you've tried
The alternative is to render all the nested components into custom elements to force Svelte into rendering the styles in-line. This is cumbersome especially when supporting both regular components and custom elements since svelte does not handle nested components for me as described in #3520.
So I'd need to create multiple versions of the same component if deeply nested.

//my element version 1
<Parent>
    ...
    <Grandchild><slot/></Grandchild>
    ....
</Parent>

// my element version 2
<my-parent>
    ....
        <my-grandchild><slot/></my-grandchild>
    ....
</my-parent>

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions