Skip to content

Search documentation

Find Svelte Patterns and Svelte reference pages.

No results for ""

Try a shorter query or a related Svelte term.

# Describe the problem

CSS encapsulation is a critical feature of single file components in Svelte; it allows you to think only about the styles that live together in a given component. Managing CSS has long been one of the more challenging aspects of building for the web; we have no desire to bring those problems back via official APIs that encourage the de-scoping of CSS. We do not wish to revisit the age of namespaced CSS selectors and required preprocessors.

pngwn

# Component Styles

<script>
	import Box from './Box.svelte'
</script>

<div class="boxes">
	<Box --color="red" />
	<Box --color="green" />
	<Box --color="blue" />
</div>
<div class="box"></div>

<style>
	.box {
		background-color: var(--color, #ddd);
	}
</style>

# How to get around it

You can work around by using the :global selector.

# Single Selector

<style>
	div :global(strong) {
		/* applies to all <strong> elements, in any component,
		   that are inside <div> elements belonging
		   to this component */
		color: goldenrod;
	}
</style>

https://svelte.dev/docs/svelte/global-styles#:global()

# Group of Selectors

<style>
	:global {
		/* applies to every <div> in your application */
		div {
			color: red;
		}

		/* applies to every <p> in your application */
		p {
			color: red;
		}
	}

	.a :global {
		/* applies to every `.b .c .d` element, in any component,
		   that is inside an `.a` element in this component */
		.b .c .d {
			color: red;
		}
	}
</style>

https://svelte.dev/docs/svelte/global-styles#:global()

# Whole Stylesheet (external)

div {
	color: red;
}
<script>
	import '../app.css'
</script>

# Whole Stylesheet (inline)

Whole stylesheet is possible via svelte-preprocess.

<style global>
	div {
		color: red;
	}
</style>