0
0
Svelteframework~30 mins

CSS custom properties (variables) in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Using CSS Custom Properties in Svelte
📖 Scenario: You are building a simple Svelte component for a website that needs consistent colors and spacing. Using CSS custom properties (variables) helps keep the design easy to update and maintain.
🎯 Goal: Create a Svelte component that uses CSS custom properties to define colors and spacing. Then apply these variables to style the component's elements.
📋 What You'll Learn
Create CSS custom properties for --main-color and --padding inside a <style> block
Set --main-color to #3498db and --padding to 1rem
Use the var(--main-color) and var(--padding) variables to style a <div> background color and padding
Add a heading inside the <div> that uses the custom color
💡 Why This Matters
🌍 Real World
CSS custom properties let you keep design consistent and easy to update across a website or app. Using them in Svelte components helps build reusable, maintainable UI parts.
💼 Career
Front-end developers often use CSS variables with frameworks like Svelte to create scalable styles and dynamic themes. This skill is important for building modern, maintainable web apps.
Progress0 / 4 steps
1
Create CSS custom properties
Inside the <style> block, create CSS custom properties --main-color set to #3498db and --padding set to 1rem inside the :root selector.
Svelte
Hint

Use the :root selector to define global CSS variables. Write --main-color: #3498db; and --padding: 1rem; inside it.

2
Add a config variable for the background color
Create a backgroundColor variable in the <script> block and set it to var(--main-color) as a string.
Svelte
Hint

Inside the <script> block, write let backgroundColor = "var(--main-color)"; to store the CSS variable as a string.

3
Apply CSS variables to style the div
In the <style> block, style the div to use background-color: var(--main-color); and padding: var(--padding);.
Svelte
Hint

Inside the div style, write background-color: var(--main-color); and padding: var(--padding); to use the CSS variables.

4
Use the backgroundColor variable in the div style attribute
Add a style attribute to the div element and set it to background-color: {backgroundColor} to use the variable from the script.
Svelte
Hint

Add style="background-color: {backgroundColor}" to the div tag to apply the script variable as inline style.