3.6 CSS Custom Properties
In modern web development, design tokens are crucial for maintaining consistency across design systems. These named entities, which store visual design attributes like colors, spacing, and typography, are effectively implemented in CSS using custom properties (also known as CSS variables).
Saving and Managing CSS Custom Properties
CSS custom properties are typically defined within a :root selector to ensure global scope across the entire document:
:root {
--primary-color: #0066CC;
--secondary-color: #A3B9CF;
--border-radius: 8px;
}Once defined, these custom properties can be accessed anywhere in the stylesheet using the var() function. The var() function retrieves the value of a custom property, allowing for consistent reuse and easy updates across multiple rules:
.button {
color: var(--primary-color);
background-color: var(--secondary-color);
border-radius: var(--border-radius);
}The var() function also supports fallback values, which are used if the referenced custom property is not defined:
.card {
background-color: var(--secondary-color, #A3B9CF);
}By leveraging custom properties and the var() function, stylesheets become more maintainable, as changes to a property’s value in the :root will automatically propagate throughout the entire CSS, reducing duplication and the risk of inconsistencies (MDN, 2025f).
Modern CSS Functions in Custom Properties
Modern CSS functions, such as color-mix() and light-dark(), and gradient functions, such as linear-gradient(), radial-gradient(), and conic-gradient(), can also be defined as custom properties.
:root {
--brand-gradient: color-mix(in srgb, #0066cc 70%, #ff6600 30%);
--background: light-dark(#ffffff, #222222);
--linear-gradient: linear-gradient(90deg, #0066cc, #ff6600);
--radial-gradient: radial-gradient(circle, #0066cc, #ff6600);
--conic-gradient: conic-gradient(from 90deg, #0066cc, #ff6600);
}By storing the results of these modern CSS functions and gradients in custom properties, design systems gain flexibility and maintainability, as these design tokens can be easily reused and updated across the entire stylesheet using the var() function.
Last updated