Styling

Back

Loading concept...

🎨 Svelte Styling: Dress Up Your Components!

The Story of the Magic Paintbox

Imagine you have a magic paintbox. When you paint something with it, the color only sticks to what YOU painted—not to your friend’s drawing next to yours. That’s exactly how Svelte styling works!

In Svelte, every component gets its own private paintbox. Your colors won’t accidentally splash onto other components. Let’s learn all the magical tricks!


🏠 Scoped CSS: Your Private Room

Think of your Svelte component like your bedroom. When you decorate it, the decorations stay in YOUR room—they don’t magically appear in your sister’s room!

How It Works

When you write CSS inside a <style> block in Svelte, it only affects that component:

<style>
  p {
    color: blue;
    font-size: 18px;
  }
</style>

<p>I am blue!</p>

Even though we said “all p tags should be blue,” this only makes p tags in THIS component blue. Other components keep their own styles!

The Magic Behind It

Svelte adds a special secret code to your elements (like class="svelte-xyz123"). It’s like putting a name tag on everything in your room so the paint knows where to go!

graph TD A["You write: p color blue"] --> B["Svelte adds secret code"] B --> C["p.svelte-abc123 color blue"] C --> D["Only YOUR p tags turn blue!"]

🌍 Global CSS: Painting the Whole House

Sometimes you want to paint the entire house, not just your room. That’s when you use Global CSS!

Method 1: Global Style Block

Add :global to make styles apply everywhere:

<style>
  :global(body) {
    font-family: 'Karla', sans-serif;
    background: #f5f5f5;
  }
</style>

This paints the WHOLE app’s body—not just this component!

Method 2: External Stylesheet

Put your global styles in a separate .css file and import it:

// In your main.js or App.svelte
import './global.css';

🎯 The :global Selector: The Master Key

The :global() selector is like a master key that unlocks any door in the house!

Using :global Inside Scoped Styles

You can mix scoped and global in one style block:

<style>
  .container {
    padding: 20px;
  }

  .container :global(h1) {
    color: purple;
  }
</style>

<div class="container">
  <h1>I'm purple everywhere!</h1>
</div>

Pattern: Parent Scope + Global Child

<style>
  .card :global(.icon) {
    width: 24px;
  }
</style>

The .card is scoped (private), but .icon inside it affects ALL icons!


🏷️ Class Directive: Smart Labels

The class directive is like putting smart stickers on your toys. You can add or remove stickers based on rules!

Basic Usage

<script>
  let isActive = true;
</script>

<button class:active={isActive}>
  Click me!
</button>

<style>
  .active {
    background: green;
    color: white;
  }
</style>

When isActive is true, the button gets the active class. When false, it disappears!

Shorthand: Same Name Magic

If your variable name matches the class name, use the shorthand:

<script>
  let active = true;
  let disabled = false;
</script>

<!-- Same as class:active={active} -->
<button class:active class:disabled>
  Magic!
</button>

🎭 Conditional Classes: Costume Changes

Conditional classes are like costume changes in a play. Your element wears different outfits based on what’s happening!

Multiple Conditions

<script>
  let size = 'large';
  let theme = 'dark';
</script>

<div
  class:large={size === 'large'}
  class:small={size === 'small'}
  class:dark={theme === 'dark'}
  class:light={theme === 'light'}
>
  I change costumes!
</div>

Combining with Regular Classes

<button
  class="btn primary"
  class:loading
  class:success={isDone}
>
  Submit
</button>

The btn and primary classes always stay. loading and success come and go!

graph TD A["Button"] --> B{loading = true?} B -->|Yes| C["Add loading class"] B -->|No| D["Remove loading class"] A --> E{isDone = true?} E -->|Yes| F["Add success class"] E -->|No| G["Remove success class"]

🖌️ Style Directive: Inline Magic

The style directive lets you set CSS properties directly with JavaScript values. It’s like having a remote control for your styles!

Basic Usage

<script>
  let color = 'coral';
  let size = 24;
</script>

<p style:color style:font-size="{size}px">
  I'm dynamic!
</p>

Multiple Styles

<script>
  let bg = '#3498db';
  let textColor = 'white';
  let padding = 16;
</script>

<div
  style:background-color={bg}
  style:color={textColor}
  style:padding="{padding}px"
>
  Fully customizable!
</div>

Important Flag

Need to override other styles? Use !important:

<p style:color|important="red">
  I'm ALWAYS red!
</p>

đź”® CSS Variables in Components: The Magic Wands

CSS Variables are like magic wands that can change multiple things at once! Change one variable, and everything using it updates!

Defining Variables

<style>
  .theme {
    --primary: #667eea;
    --secondary: #764ba2;
    --spacing: 16px;
  }

  .button {
    background: var(--primary);
    padding: var(--spacing);
  }

  .link {
    color: var(--secondary);
  }
</style>

Passing Variables from JavaScript

Here’s the superpower: You can set CSS variables with JavaScript!

<script>
  let primaryColor = '#e74c3c';
  let borderRadius = 8;
</script>

<div
  class="card"
  style:--card-color={primaryColor}
  style:--radius="{borderRadius}px"
>
  <p>Dynamic theming!</p>
</div>

<style>
  .card {
    background: var(--card-color);
    border-radius: var(--radius);
    padding: 20px;
  }
</style>

Theme Switching Example

<script>
  let isDark = false;
</script>

<div
  class="app"
  style:--bg={isDark ? '#1a1a2e' : '#ffffff'}
  style:--text={isDark ? '#ffffff' : '#333333'}
>
  <button on:click={() => isDark = !isDark}>
    Toggle Theme
  </button>
</div>

<style>
  .app {
    background: var(--bg);
    color: var(--text);
    transition: all 0.3s ease;
  }
</style>
graph TD A["JavaScript Variable"] --> B["style:--variable"] B --> C["CSS Variable Created"] C --> D["Used in var function"] D --> E["Applied to Element!"]

🎯 Quick Summary

Feature What It Does Example
Scoped CSS Styles stay in component <style> p { } </style>
Global CSS Styles go everywhere :global(body) { }
:global Escape scope for specific rules .parent :global(.child)
class: Toggle classes with conditions class:active={isOn}
Conditional Multiple class toggles class:big class:red
style: Inline dynamic properties style:color={myColor}
CSS Vars Reusable, dynamic values style:--theme={color}

đź’ˇ Pro Tips

  1. Start Scoped: Always use scoped CSS by default. Go global only when needed.

  2. Name Your Variables: Use clear names like --primary-color, not --c1.

  3. Combine Powers: Mix class: directives with CSS variables for ultimate flexibility!

  4. Transitions: CSS variables work beautifully with transitions:

    <style>
      .box {
        background: var(--bg);
        transition: background 0.3s;
      }
    </style>
    

🚀 You Did It!

You now know all the styling superpowers in Svelte:

  • 🏠 Scoped CSS keeps styles private
  • 🌍 Global CSS paints the whole app
  • 🎯 :global is your escape hatch
  • 🏷️ class: toggles classes smartly
  • 🎭 Conditional classes for costume changes
  • 🖌️ style: for inline dynamics
  • đź”® CSS Variables for magical theming

Go forth and make beautiful, well-organized, dynamic styles! Your components will thank you! 🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.