javascripthtmlcsscomponentssvelte

Svelte styles are not applied to scope


I have a problem with adding styles in my Svelte components. I want to make sure that my styles are only applied within a specific component, but it doesn't work.

Here is an example of a component. There is the <style> inside the component tag, so it will be applied globally (this works - all elements of type button in the entire application get red):

<script>
    import { Button } from "flowbite-svelte";
</script>

<div>
    <Button>Test Button</Button>

    <style>
        button {
            background-color: red;
        }
    </style>
</div>

According to the Svelte documentation, I should be able to place the <style> tag outside of the HTML Elements in the file to apply the style only to the current component.

Here is my updated code:

<script>
    import { Button } from "flowbite-svelte";
</script>

<div>
    <Button>Test Button</Button>
</div>

<style>
    button {
        background-color: red;
    }
</style>

However, I get the following error:

Unused CSS selector "button"svelte(css-unused-selector)

How can I ensure that my styles are restricted locally to the component?


Solution

  • The actual button is hidden within the Button component, so it falls outside the scope of the current component. You can work around that via global styles which can be scoped to just descendants using a scoped local element as parent, e.g.

    <div>
        <Button>Test Button</Button>
    </div>
    
    <style>
        div :global(button) {
            background-color: red;
        }
    </style>
    

    (You can of course use any other selector, e.g. add a class to your element so you don't target any div in the component.)

    Style docs