Category: html_css
CSS variables
Published on 29 Jun 2026
Explanation
CSS variables, also called custom properties, allow you to store reusable values such as colors, fonts, and spacing.
Code:
:root {
--primary-color: blue;
}
Explanation
Variables are accessed using the var() function, making styles easier to maintain.
Code:
h1 {
color: var(--primary-color);
}
Explanation
Multiple variables can be defined in the :root selector for use throughout the entire website.
Code:
:root {
--primary: #2563eb;
--secondary: #10b981;
--padding: 20px;
}
Explanation
CSS variables simplify theme changes because updating the variable automatically updates every element that uses it.
Code:
button {
background: var(--primary);
padding: var(--padding);
}
Explanation
Variables can also include fallback values if the custom property is not defined.
Code:
p {
color: var(--text-color, black);
}