Scoped global CSS

Sometimes your template code doesn’t match your CSS. If you generate html via {@html} or have some un-styled elements inside child components, you might want to style it. However, Svelte won’t let you write CSS that doesn’t exist in the templates. You might feel forced to use :global() to make the CSS work, but that would leak it out to the rest of your app. So, instead you could try this trick:

<div>
	<Paragraph />
	<Paragraph />
	<Paragraph />
</div>

<style>
	div :global(p + p) {
		margin-top: 1rem;
	}
</style>

Now that p styling will be output by Svelte, AND it won’t leak out to the rest of your app.

Published: