0
0
Svelteframework~5 mins

CSS custom properties (variables) in Svelte

Choose your learning style9 modes available
Introduction

CSS custom properties let you store values like colors or sizes in one place. This makes it easy to reuse and change them across your styles.

You want to keep your color scheme consistent across your app.
You need to change a font size in many places quickly.
You want to create themes that users can switch between.
You want to adjust spacing or layout values easily.
You want to avoid repeating the same CSS values multiple times.
Syntax
Svelte
:root {
  --main-color: #3498db;
  --padding: 1rem;
}

.element {
  color: var(--main-color);
  padding: var(--padding);
}

Custom properties start with two dashes --.

Use var(--property-name) to access the value.

Examples
Define a color variable and use it for a button background.
Svelte
:root {
  --primary-color: #ff6347;
}

button {
  background-color: var(--primary-color);
}
Use the same spacing value for margin and padding.
Svelte
:root {
  --spacing: 2rem;
}

.container {
  margin: var(--spacing);
  padding: var(--spacing);
}
Set a font size variable and apply it to headings.
Svelte
:root {
  --font-size: 1.2rem;
}

h1 {
  font-size: var(--font-size);
}
Sample Program

This Svelte component uses a CSS custom property --theme-color to set the background color of a box. Changing the variable in :root updates the color everywhere it is used.

Svelte
<script>
  let themeColor = '#4caf50';
</script>

<style>
  :root {
    --theme-color: #4caf50;
  }

  .box {
    background-color: var(--theme-color);
    color: white;
    padding: 1rem;
    border-radius: 0.5rem;
    text-align: center;
  }
</style>

<div class="box">
  This box uses a CSS variable for its background color.
</div>
OutputSuccess
Important Notes

You can update CSS variables dynamically with JavaScript or Svelte reactive statements.

Custom properties cascade like normal CSS, so you can override them in specific elements.

They work well with media queries for responsive design.

Summary

CSS custom properties store reusable style values.

Use var(--name) to access them.

They make styling easier to maintain and update.