svelte icon indicating copy to clipboard operation
svelte copied to clipboard

Add CSS selector to target top-level component elements e.g. `:scope`

Open Bilge opened this issue 1 year ago • 3 comments

Describe the problem

We can target the root element when it's the only element of that tag.

<div>
  <span/>
</div>

<style lang="less">
  div { color: red; } // Targets root element.
</style>

However, when the element appears more than once, we can no longer do this.

<div>
  <div/>
</div>

<style lang="less">
  div { color: red; } // Too red!
</style>

Specifying a class name may collide with external styles. I've tried :root and :scope but they don't seem to work.

Describe the proposed solution

<style lang="less">
  :scope { color: red; } // Only affects root element.
</style>

Importance

would make my life easier

Bilge avatar Feb 13 '24 10:02 Bilge

There is not a single top-level element. You can have arbitrary elements on the top level. Which one will be selected by :sope?

KevsRepos avatar Feb 13 '24 11:02 KevsRepos

In that case, :scope should refer to a (virtual) root element for the component, and my example would then become the following.

<style lang="less">
  :scope > div { color: red; } // Only affects top-level div element.
</style>

Bilge avatar Feb 13 '24 11:02 Bilge

But there are no elements to refer to as :scope during compile time. Theoretically, *:not(* *) should select only top-level components but it gets compiled into .svelte-103htr2:not(* *) so it doesn't work.

And in the following markup:

<Component>
  <div>
    <span></span>
  </div>
</Componet>

what should refer :scope or :scope > *?

What's wrong with adding classes to the top-level elements?

7nik avatar Feb 13 '24 12:02 7nik