CSS Variables Reference
CSS custom properties and variables for dynamic styling
Defining Variables
:root { # global scope
--primary-color: #007bff;
--secondary-color: #6c757d;
--font-size: 16px;
--spacing: 1rem;
}
.container { # local scope
--container-width: 1200px;
}
Using Variables
background-color: var(--primary-color); # basic usage
color: var(--text-color, #333); # with fallback
padding: var(--spacing) calc(var(--spacing) * 2); # with calc
font-size: calc(var(--font-size) * 1.5); # calculations
Dynamic Updates
# JavaScript manipulation
document.documentElement.style
.setProperty("--primary-color", "#ff0000"); # change value
const color = getComputedStyle(document.documentElement)
.getPropertyValue("--primary-color"); # get value
Media Query Variables
:root {
--columns: 1; # mobile default
}
@media (min-width: 768px) {
:root {
--columns: 3; # desktop columns
}
}
.grid {
grid-template-columns: repeat(var(--columns), 1fr);
}
Theming Example
# Light theme
[data-theme="light"] {
--bg-color: #ffffff;
--text-color: #333333;
}
# Dark theme
[data-theme="dark"] {
--bg-color: #1a1a1a;
--text-color: #f0f0f0;
}