CSS Selectors for components - Svelte

I can’t seem to select components in order to style using CSS with either ID’s or classes? How do you style components? I know I can use :global to get around it, or even use normal elements (ie. button rather than Button) but is there a way to make use of the ability to scope css in svelte?

I understand this is to do with the components compiled output being different and svelte removing what it thinks is unnecessary css, but how do I do something as simple as…

  <Button id="my-button">Press me</Button> <--- Doesn't work
  <button id="my-button">Press me</button> <--- Does work
  #my-button {background: red;} <--- Works on element but not component
  :global(#my-button){background: red;} <--- Works but not scoped

What am I missing?!!

Not sure how scoped styles work in Svelte, but using :global is what i came up too

The svelte compiler will always run a tree shake process while compiling your code, which means it will always remove unused scoped css.

Svelte will trace attributes only from html pure elements and will ignore any Components’ attributes while tree shaking the css.

So this means that

<Button id=“my-button”>Press me</Button>

the “id” attribute is actually not an html attribute, but a property of the Button component.

As far as the compiler is concerned, the “id” attribute doesn’t even exist in your svelte file.

I’m not exactly sure if this is a design choice for svelte, but when you think about it more it makes sense: not all your component properties are html attributes and the compiler doesn’t have a specific way to distinguish between attributes and properties.

I believe there are open issues on the svelte github repo right now and it’s something we’ve been asking for some time, but it’s not yet implemented, mainly because they’ve been focused on dishing out TypeScript support for svelte, which has just been released.

Soon? Maybe.

Until then the workaround is to use :global(…), which tells the compiler to just include that part in your css bundle without scoping it regardless if it exists in the current file or not.

1 Like