0
0
SvelteHow-ToBeginner · 3 min read

How to Use :global in Svelte for Global CSS Styling

In Svelte, use :global in your style blocks to apply CSS rules globally instead of scoping them to the component. Wrap selectors with :global( ... ) to target elements outside the component or to style global classes and tags.
📐

Syntax

The :global selector in Svelte is used inside a component's <style> block to write CSS rules that apply globally rather than being scoped locally.

Use it by wrapping selectors like :global(selector). You can also write :global once to start a global block.

  • :global(.class) targets a global class.
  • :global(div) targets a global tag.
  • :global { ... } applies all enclosed styles globally.
css
<style>
  /* Global class selector */
  :global(.my-global-class) {
    color: red;
  }

  /* Global tag selector */
  :global(h1) {
    font-weight: bold;
  }

  /* Global block for multiple selectors */
  :global {
    body {
      background: #f0f0f0;
    }
    p {
      font-size: 1.2rem;
    }
  }
</style>
💻

Example

This example shows how to style a global class and a global HTML tag from inside a Svelte component using :global. The styles apply outside the component's scope.

svelte
<script>
  // No JavaScript needed for this example
</script>

<style>
  /* Style a global class */
  :global(.highlight) {
    background-color: yellow;
  }

  /* Style a global tag */
  :global(h2) {
    color: teal;
  }

  /* Local style scoped to this component */
  p {
    font-style: italic;
  }
</style>

<h2>This is a global styled heading</h2>
<p class="highlight">This paragraph has a global highlight background.</p>
<p>This paragraph is locally styled italic.</p>
Output
A teal colored <h2> heading, a paragraph with yellow background from the global class, and another paragraph italic styled locally.
⚠️

Common Pitfalls

Common mistakes when using :global include:

  • Forgetting to wrap selectors inside :global( ... ) or a :global { ... } block, causing styles to be scoped locally unintentionally.
  • Using :global on selectors that should remain scoped, leading to unexpected style leaks.
  • Trying to use :global outside of a <style> block, which is invalid.
css
<style>
  /* Wrong: missing :global, styles scoped locally */
  .button {
    color: blue;
  }

  /* Right: global class selector */
  :global(.button) {
    color: blue;
  }
</style>
📊

Quick Reference

UsageDescriptionExample
:global(selector)Apply styles globally to the selector:global(.my-class) { color: red; }
:global { ... }Apply multiple styles globally inside the block:global { body { margin: 0; } h1 { font-size: 2rem; } }
Local stylesStyles scoped to the component onlyp { color: blue; }
Incorrect usageForgetting :global causes local scoping.button { color: green; }

Key Takeaways

Use :global inside