0
0
SvelteHow-ToBeginner · 3 min read

How to Use Global Styles in Svelte: Simple Guide

In Svelte, you can use global styles by wrapping CSS selectors with :global() inside a component's <style> tag or by importing external CSS files in your project. The :global() selector ensures styles apply globally instead of being scoped to the component.
📐

Syntax

To write global styles inside a Svelte component, use the :global() pseudo-selector inside the <style> block. This tells Svelte not to scope these styles to the component only.

You can also write plain CSS in external files and import them globally in your app entry point.

svelte
<style>
  /* Global style for all paragraphs */
  :global(p) {
    color: blue;
    font-weight: bold;
  }

  /* Scoped style for this component only */
  h1 {
    color: red;
  }
</style>
💻

Example

This example shows how to make all p tags blue globally using :global(), while keeping the h1 style scoped to the component.

svelte
<script>
  // No JavaScript needed for styles
</script>

<style>
  :global(p) {
    color: blue;
    font-weight: bold;
  }

  h1 {
    color: red;
  }
</style>

<h1>This is a red heading</h1>
<p>This paragraph will be blue everywhere.</p>
Output
<h1 style="color: red;">This is a red heading</h1><p style="color: blue; font-weight: bold;">This paragraph will be blue everywhere.</p>
⚠️

Common Pitfalls

  • Forgetting to use :global() causes styles to be scoped only to the component, so they won't affect other components.
  • Using :global without parentheses (like :global p) is invalid; always use :global(selector).
  • Importing CSS files without configuring your build tool may not apply styles globally.
svelte
<style>
  /* Wrong: missing parentheses, won't work */
  :global p {
    color: green;
  }

  /* Correct: with parentheses */
  :global(p) {
    color: green;
  }
</style>
📊

Quick Reference

FeatureUsageEffect
:global(selector)Wrap selectors in parentheses inside