Home > database >  CSS selectors not working as expected when using each and components in svelte
CSS selectors not working as expected when using each and components in svelte

Time:10-30

Why svelte declares unused CSS selector when there could be inner elements inside my Component?

<div class="container">
    {#each [1,2,3,4,5] as id}
        <User name={id} />
    {/each}
</div>

<style>
    .users > * {
        margin-right: 5px;
    }
</style>

Error: Unused CSS selector ".users > *" (12:4)

Repl: https://svelte.dev/repl/6c8b4a6a808c4aee80e51af58b4fcda4?version=3.44.0

User is a regular div. Not sure if I should use another pattern to achieve this.

CodePudding user response:

Multiple things:

  • I don't see a users class in your code, the div has a class container, I guess you meant that one
  • Svelte scopes all styles to the current component, which means elements of children are not targeted. In your case, you want to target any direct child of your div, but the elements are inside User, so this doesn't work

Solution: Use :global which tells Svelte to not scope the selector to the current component:

<script>
import User from './User.svelte'
</script>

<div class="users">
    {#each [1,2,3,4,5] as id}
        <User name={id} />
    {/each}
</div>

<style>
    /* you could also write :global(.users > *) but that
       would also target any "users" class somewhere else */
    .users > :global(*) {
        border: 3px solid teal;
    }
</style>

CodePudding user response:

In Svelte the css is scoped to the component by default, so styles defined inside a component will have no effect anywhere else. (the styled elements inside a component get an additional class like 'svelte-1g7lik1')

The 'users' div is except for the User component - which is not affected by the styling - empty, so the declaration has no effect on anything and hence is redundant

You can solve the problem by wrapping your css statement in :global()

See this REPL

<script>
import User from './User.svelte'
</script>

<div class="users">
    {#each [1,2,3,4,5] as id}
        <User name={id} />
    {/each}
</div>

<style>
    .users > :global(*){
      border: 3px solid teal;
    }

    /*>> .users.svelte-16kesww>* {...} in bundle.css  */
      >> affects 'childcomponent-children'

  
    :global(.users > *) {  
        box-shadow: 2px 3px 0 0 pink;
    }

    /*>> .users > * {...} in bundle.css
      >> affects globally all children of elements with class 'users' */
</style>
  • Related