🎨
CSS Custom Properties (Variables)
Intermediate
100 XP
35 min
Lesson Content
CSS Custom Properties (Variables)
CSS custom properties (also called CSS variables) allow you to store values that can be reused throughout your stylesheet. They make it easy to maintain consistent design and create themes.
Defining Variables
Variables are defined using -- prefix and are typically defined in :root for global access:
:root {
--primary-color: #3b82f6;
--secondary-color: #10b981;
--font-size: 16px;
--spacing: 20px;
}Using Variables
Access variables with the var() function:
.button {
background-color: var(--primary-color);
padding: var(--spacing);
font-size: var(--font-size);
}Fallback Values
Provide fallback values in case the variable isn't defined:
.element {
color: var(--text-color, #000000);
/* Uses #000000 if --text-color doesn't exist */
}Scoped Variables
Variables can be scoped to specific elements:
.card {
--card-bg: #ffffff;
--card-padding: 20px;
background-color: var(--card-bg);
padding: var(--card-padding);
}Dynamic Variables
Variables can be changed with JavaScript or media queries:
/* Change with media query */
@media (prefers-color-scheme: dark) {
:root {
--bg-color: #1f2937;
--text-color: #ffffff;
}
}
/* Change with JavaScript */
document.documentElement.style.setProperty('--primary-color', '#ef4444');Benefits
- Easy theme switching
- Consistent design values
- Easy maintenance
- Dynamic updates
Example Code
Use CSS variables to create a consistent color theme.
<!DOCTYPE html>
<html>
<head>
<style>
:root {
/* Define variables for:
- primary-color: #3b82f6
- secondary-color: #10b981
- text-color: #1f2937
- spacing: 20px
*/
}
.button {
background-color: var(--primary-color);
color: white;
padding: var(--spacing);
border: none;
border-radius: 5px;
}
.text {
color: var(--text-color);
margin: var(--spacing);
}
</style>
</head>
<body>
<button class="button">Click Me</button>
<p class="text">Styled with CSS variables</p>
</body>
</html>Expected Output:
Page using CSS variables
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code