CSS Variables

Reusable custom properties.

✍️ 3 exercises + code challenge in this lesson

CSS variables (custom properties) store values you want to reuse, such as brand colours.

  • Declare them with two dashes: --primary: #2563EB;
  • Read them with var(): color: var(--primary);
  • Declaring them on :root makes them available everywhere.
  • A fallback can be given: var(--accent, orange).

Variables can be changed in media queries or with JavaScript, which makes themes like dark mode easy.

Key Takeaways: CSS Variables

Mastering CSS Variables helps you write clean and reliable CSS code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

CSS Variables Code Example

CSS
<style>
  :root { --primary: #2563EB; --accent: #14B8A6; --radius: 10px; }
  .dark { --primary: #38BDF8; background: #071A2F; color: white; }

  .panel  { padding: 16px; border-radius: var(--radius); margin-bottom: 10px; border: 2px solid var(--primary); }
  .panel h3 { color: var(--primary); margin: 0 0 6px; }
  .btn    { background: var(--accent); color: white; border: 0; padding: 8px 14px; border-radius: var(--radius); }
</style>

<div class="panel"><h3>Light theme</h3><button class="btn">Button</button></div>
<div class="panel dark"><h3>Dark theme</h3><button class="btn">Button</button></div>
Free sign-in required · Google login available

CSS Variables Practice Exercises

Check what you learned in “CSS Variables”.

/ 3 solved
Fill in the blank

Read the custom property --brand.

button {
  background: (--brand);
}
✓ Correct! Not quite. Try again.
Multiple choice

Where should global CSS variables usually be declared?

✓ Correct! Not quite. Try again.
Code challenge

Declare --main-color: #14b8a6 on :root and use it as the colour of h1.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services