Skip to main content

The previous example contained a default slot, which renders the direct children of a component. Sometimes you will need more control over placement. In those cases, we can use named slots.

Inside App.svelte, we're rendering a <Card> component that contains <span slot="telephone"> and others for company and address. Let's add the corresponding named slots in Card.svelte:

Card.svelte
<div class="card">
	<header>
		<slot name="telephone"></slot>
		<slot name="company"></slot>
	</header>

	<slot></slot>

	<footer>
		<slot name="address"></slot>
	</footer>
</div>

We need to add some styles to the <small> element in App.svelte so that it occupies its own line. The contents of <Card> inherit styles from Card.svelte, such as font-family (the lettering is something called 'Silian Rail'), but normal scoping rules apply — we need to add the styles to App.svelte because that's where the element is:

App.svelte
<style>
	main {
		display: grid;
		place-items: center;
		height: 100%;
		background: url(./wood.svg);
	}

	small {
		display: block;
		font-size: 0.6em;
		text-align: right;
	}
</style>

Alternatively, we could use the :global modifier inside Card.svelte to target all small elements inside .card:

Card.svelte
<style>
	/* ... */

	.card :global(small) {
		display: block;
		font-size: 0.6em;
		text-align: right;
	}
</style>

Next: Slot fallbacks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script>
	import Card from './Card.svelte';
</script>
 
<main>
	<Card>
		<span>Patrick BATEMAN</span>
		<span>Vice President</span>
 
		<span slot="telephone">212 555 6342</span>
 
		<span slot="company">
			Pierce &amp; Pierce
			<small>Mergers and Aquisitions</small>
		</span>
		
		<span slot="address">358 Exchange Place, New York, N.Y. 10099 fax 212 555 6390 telex 10 4534</span>
	</Card>
</main>
 
<style>
	main {
		display: grid;
		place-items: center;
		height: 100%;
		background: url(./wood.svg);
	}
</style>
initialising