Reputation: 4181
Why svelte declares unused CSS selector when there could be inner elements inside my Component?
<div class="users">
{#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.
Upvotes: 1
Views: 1991
Reputation: 7699
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>
Upvotes: 2
Reputation: 5426
Multiple things:
users
class in your code, the div
has a class container
, I guess you meant that onediv
, but the elements are inside User
, so this doesn't workSolution: 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>
Upvotes: 5