Clean β’ Professional
CSS Variables, also known as custom properties, are a powerful feature that allows developers to store values (like colors, font sizes, spacing units) in reusable variables. This makes your stylesheets cleaner, more maintainable, and flexible.
Instead of repeating the same values everywhere in your CSS, you can define them once as variables and reuse them wherever needed. If you want to change a color or spacing later, you just update the variable in one place β and it reflects across your whole website.
The var() function is used to insert the value of a CSS variable into your stylesheet.
Syntax :
var(--variable-name, fallback-value)
-).Example:
color: var(--primary-color, blue);
:root selector (which targets the documentβs root). These are accessible throughout the entire CSS file.Example of Global Variables:
:root {
--blue: #1e90ff;
--white: #ffffff;
}
Example of Local Variables:
.card {
--card-bg: #f9f9f9;
background: var(--card-bg);
}
Without variables (traditional way):
body { background-color: #1e90ff; }
h2 { border-bottom: 2px solid #1e90ff; }
button { background-color: #ffffff; color: #1e90ff; }
With variables:
:root {
--blue: #1e90ff;
--white: #ffffff;
}
body { background-color: var(--blue); }
h2 { border-bottom: 2px solid var(--blue); }
button {
background-color: var(--white);
color: var(--blue);
border: 1px solid var(--blue);
}
CSS variables can also adapt based on device size:
:root {
--font-size: 16px;
}
@media (max-width: 600px) {
:root {
--font-size: 14px;
}
}
p {
font-size: var(--font-size);
}
Variables are part of the DOM, so you can update them dynamically:
document.documentElement.style.setProperty('--blue', '#6495ed');
Β