sveltesapper

Class styling on a custom component in Svelte does not register


I am using Svelte/Sapper templae and added Attractions UI, but I cannot apply any class/styles to their custom components, like so:

<TextField class='search-box' type='search' />
<style>
    .search-box {
        margin-bottom: 10px;
    }
</style>

I get

Unused CSS selector ".search-box"

The only way to make it work so far for me was to apply the :global modifier on the style.


Solution

  • I believe what you are trying to achieve is not currently possible in Svelte. The class prop is not treated as special in Svelte, so it does not leak the style scope into the child component, especially since there does not have to be one root element in the child component (unlike in Vue.js, for instance).

    Therefore, you cannot add styles in the parent component and expect them to reach the child component. Your only option is to use the :global modifier or add the styles to a global stylesheet (included directly in the HTML, not in a Svelte component)

    Note that you can combine :global and scoped styles. For example, consider:

    <div class='local'>
        <TextField class='search-box' type='search' />
    </div>
    
    <style>
        .local :global(.search-box) {
            margin-bottom: 10px;
        }
    </style>
    

    This way, the styles are not leaked to other components and are still scoped to this component only.