Skip to content

Optionally scope imported CSS files to component level #7125

@rodoch

Description

@rodoch

Describe the problem

Currently, when stylesheets are imported within either a script or style block within a Svelte component their styles are applied globally.

<style>
    @import 'carbon-components-svelte/css/g10.css';
</style>

This is a sensible default behaviour. Some design system libraries etc. need to touch things like the body and html elements.

However, I think this can also be problematic and a limitation in some cases. For example, if you are producing a component library you often want to make sure that all of your styles are encapsulated and do not wreak havoc with the parent webpage/app styling.

Describe the proposed solution

A solution for this currently exists in Vue, where you can do something like:

<style scoped src="@/assets/css/main.css"></style>

...and it wil scope the contents of the CSS file. This is very ergonomic.

I want to be clear, the extent of this request is in relation to imported external CSS files. In researching this issue, I came across some rather in-depth debates as regards providing a scoped/unscoped modifier for the style block. I am not trying to rehash this debate here and I'm not wedded to this particular approach, I'm just using it as an example of an equivalent functionality in another popular framework.

Futhermore, given that Svelte does not wrap components in a generic div in the generated HTML I can see reasons why this may be difficult to implement. But given the potential benefits for users I thought I should ask the question at least.

Alternatives considered

  1. Don't implement it: In this case, I think the current behaviour could at least be better documented. Given that most people associate Svelte with effective style encapsulation, this behaviour with imported CSS can come as a surprise to people, certainly it took me a minute to work it out.
  2. Perhaps this can be solved in userland with a preprocessor? I tried to see if I could get this to work with PostCSS but it's proved beyond my skills so far.

Importance

would make my life easier

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions