CHAPTER 44
CSS Variables
Learn how custom CSS properties can store reusable values such as colors, spacing and font sizes.
01. What is CSS Variables?
CSS variables are custom properties that store reusable CSS values.
They are commonly declared using names beginning with two hyphens.
The var() function retrieves a variable value.
Variables make large stylesheets easier to maintain.
02. Syntax
:root {
--primary-color: #2563eb;
--spacing: 20px;
}
button {
background: var(--primary-color);
padding: var(--spacing);
}
03. Example
CSS / HTML Example
AIFA Coding Lab
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--primary: #2563eb;
--dark: #020617;
--space: 20px;
}
.card {
padding: var(--space);
background: var(--dark);
color: white;
}
button {
padding: 12px 20px;
background: var(--primary);
color: white;
border: none;
}
</style>
</head>
<body>
<div class="card">
<h2>AIFA Coding Lab</h2>
<button>
Learn CSS
</button>
</div>
</body>
</html>
04. Important Points
✓
Custom properties commonly start with --.
✓
:root is useful for global variables.
✓
var() retrieves a variable.
✓
Variables can be changed in one place and reused throughout a stylesheet.
✓
Variables can also be overridden inside specific elements.
05. Common Mistakes
⚠
Using a variable that has not been defined.
⚠
Creating too many variables with unclear names.
⚠
Using inconsistent naming conventions.
06. Real World Use
CSS variables are widely used for brand colors, dark mode, spacing systems, typography and design systems.
Ready to Practice? 🚀
Open the AIFA CSS Editor and practice this chapter live.
Try It Yourself →
Practice Exercise
Create a CSS Theme
Create variables for primary color, secondary color and spacing. Use them to design a card and button.