0
0
SvelteHow-ToBeginner · 4 min read

How to Use CSS Variables in Svelte: Simple Guide

In Svelte, you can use CSS variables by defining them inside a <style> block or globally, then referencing them in your styles with var(--variable-name). You can also update these variables dynamically using inline styles or reactive variables in your component.
📐

Syntax

Define CSS variables inside a <style> block using --variable-name: value;. Use them in CSS properties with var(--variable-name). You can set variables globally on :root or locally on elements.

css
:root {
  --main-color: #4caf50;
}

div {
  color: var(--main-color);
  background-color: var(--bg-color, white); /* fallback to white */
}
💻

Example

This example shows how to define a CSS variable in a Svelte component and use it in styles. It also demonstrates changing the variable dynamically with a button click.

svelte
<script>
  let color = '#ff6347';
  function changeColor() {
    color = color === '#ff6347' ? '#4682b4' : '#ff6347';
  }
</script>

<style>
  div {
    color: var(--text-color);
    border: 2px solid var(--text-color);
    padding: 1rem;
    font-weight: bold;
    width: max-content;
    cursor: pointer;
    user-select: none;
  }
</style>

<div style="--text-color: {color}" on:click={changeColor} aria-label="Change text color">
  Click me to change color
</div>
Output
A clickable box with text 'Click me to change color' that toggles text and border color between tomato red and steel blue on each click.
⚠️

Common Pitfalls

  • Forgetting to use var(--variable-name) when referencing CSS variables.
  • Defining variables only in :root but expecting local overrides without inline styles.
  • Not updating CSS variables dynamically via inline styles or reactive bindings in Svelte.
  • Using CSS variables in JavaScript without accessing computed styles.
css
<!-- Wrong: Using variable name directly -->
<style>
  div {
    color: --main-color; /* Incorrect, missing var() */
  }
</style>

<!-- Right: Use var() -->
<style>
  div {
    color: var(--main-color);
  }
</style>
📊

Quick Reference

ActionSyntax / Notes
Define global variable:root { --name: value; }
Define local variableselector { --name: value; }
Use variableproperty: var(--name, fallback);
Set variable dynamically
Update variable in SvelteUse reactive variable in inline style binding

Key Takeaways

Define CSS variables inside