Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply styles to slot element in Svelte?

Tags:

svelte

I'd like styles declared in one module to be applied to the slot elements of that module (which get filled in in another file).

Here's a Svelte REPL of the following example:

App.html

<List>
    {{#each items as item}}
        <li><a>{{item}}</a></li>
    {{/each}}
</List>

<script>
    import List from './List.html'

    export default {
        components: {
            List
        }
    }
</script>

List.html:

<h1>A Special List</h1>
<ul>
    <li><a>Let's all be red!</a></li>
    <slot></slot>
</ul>

<style>
    ul a {
        color: red;
    }
</style>

Data:

{
    "items": ["Nope", "I'm good"]
}

The red coloring doesn't apply to the a tag elements that were added through slot.

I'm very new to Svelte, but I read through as much as I could find online, and couldn't seem to find a solution. Any help would be appreciated, thank you.

like image 797
jeremye Avatar asked Sep 07 '17 01:09

jeremye


People also ask

Is Svelte CSS scoped?

With Svelte you are not forced to be using scoped CSS styling. In fact, you can be using the traditional CSS files like you used to, or you can be using the :global selector inside your <style> tags to write CSS that will target elements globally in your project.

What is Svelte slot?

svelte:fragment allows you to place content in a named slot without wrapping it in a container DOM element. This keeps the flow layout of your document intact. Let's refactor the Card component with svelte:fragment : <Card> <svelte:fragment slot="header"> <h1>Card title</h1> <p>Card date</p> </svelte:fragment> </Card>


1 Answers

The trick here is to opt in to the cascade, using the :global(...) modifier. In your List component:

<style>
  ul :global(a) {
    color: red;
  }
</style>

That means 'any a elements that are children of this component's ul element, whether they belong to this component or not, should be red'.

like image 96
Rich Harris Avatar answered Oct 28 '22 23:10

Rich Harris