0
0
Svelteframework~30 mins

Global vs scoped style strategies in Svelte - Hands-On Comparison

Choose your learning style9 modes available
Global vs Scoped Style Strategies in Svelte
📖 Scenario: You are building a simple Svelte app with two components. One component should have styles that only apply inside it (scoped styles). The other component should have styles that apply globally across the whole app.
🎯 Goal: Create two Svelte components: ScopedButton.svelte with scoped styles and GlobalButton.svelte with global styles. Then use both components in App.svelte to see how styles behave differently.
📋 What You'll Learn
Create a ScopedButton.svelte component with a button styled using scoped CSS
Create a GlobalButton.svelte component with a button styled using global CSS
Use both components inside App.svelte
Observe how scoped styles affect only their component and global styles affect the whole app
💡 Why This Matters
🌍 Real World
Web developers often need to style components so that some styles stay inside a component and others apply globally. This helps keep apps organized and prevents style conflicts.
💼 Career
Understanding scoped vs global styles is essential for frontend developers working with Svelte or similar frameworks to build maintainable user interfaces.
Progress0 / 4 steps
1
Create ScopedButton.svelte with scoped styles
Create a Svelte component file named ScopedButton.svelte. Inside it, add a <button> element with the text Scoped Button. Add a <style> block with scoped CSS that sets the button's background color to lightblue and text color to darkblue. Use normal scoped styles (no global keyword).
Svelte
Hint

Remember, styles inside <style> in Svelte are scoped by default. Just write normal CSS targeting the button.

2
Create GlobalButton.svelte with global styles
Create a Svelte component file named GlobalButton.svelte. Inside it, add a <button> element with the text Global Button. Add a <style> block with CSS that sets the button's background color to lightgreen and text color to darkgreen. Use the :global() selector so these styles apply globally.
Svelte
Hint

Use :global(selector) in Svelte styles to make CSS rules apply globally.

3
Use both buttons in App.svelte
In App.svelte, import ScopedButton and GlobalButton components. Add both components inside the main markup so they render one after the other.
Svelte
Hint

Use import statements to bring components into App.svelte. Then add them as tags inside the markup.

4
Add global style to App.svelte for body background
In App.svelte, add a <style> block. Inside it, add a global style using :global(body) that sets the background color to #f0f0f0. This style should apply to the whole page.
Svelte
Hint

Use :global(body) in the style block to apply styles to the whole page body.