0
0
Svelteframework~5 mins

Global styles in Svelte

Choose your learning style9 modes available
Introduction

Global styles let you set CSS rules that apply to the whole app. This helps keep your look consistent everywhere.

You want all buttons in your app to have the same color and font.
You need to set a background color or font for the entire page.
You want to style HTML elements like <code>body</code> or <code>h1</code> globally.
You want to add a CSS reset or normalize styles across browsers.
You want to define fonts or colors once and use them everywhere.
Syntax
Svelte
<style global>
  /* CSS rules here apply globally */
  body {
    margin: 0;
    font-family: Arial, sans-serif;
  }
</style>
Use the global attribute on the <style> tag to make styles apply globally.
Without global, styles in Svelte components are scoped only to that component.
Examples
This sets the background color for the whole page.
Svelte
<style global>
  body {
    background-color: #f0f0f0;
  }
</style>
All <h1> headings in the app will be dark blue.
Svelte
<style global>
  h1 {
    color: darkblue;
  }
</style>
This styles paragraphs only inside this component, not globally.
Svelte
<style>
  p {
    color: red;
  }
</style>
Sample Program

This example sets a light teal background and a font for the whole page. The heading color is also set globally. The styles apply everywhere, not just inside this component.

Svelte
<script>
  let name = 'Friend';
</script>

<style global>
  body {
    background-color: #e0f7fa;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    margin: 0;
    padding: 2rem;
  }

  h1 {
    color: #00796b;
  }
</style>

<h1>Hello, {name}!</h1>
<p>Welcome to your Svelte app with global styles.</p>
OutputSuccess
Important Notes

Global styles affect all components, so use them carefully to avoid unexpected changes.

For component-specific styles, omit the global attribute to keep styles scoped.

You can combine global styles with scoped styles in the same component by using multiple <style> tags.

Summary

Global styles apply CSS rules to the entire app or page.

Use <style global> in Svelte to write global CSS.

Global styles help keep your app's look consistent everywhere.