Custom properties, sometimes referred to as CSS variables or cascading variables enable developers to reuse defined values in properties throughout the web application style sheet. The variables are defined in the :root style sheet and automatically inherited by the style sheets in the app. The variables are prepended with ‘–‘ like ‘–text-color’ and referenced like this in the style sheet: color: var(–text-color);

Most web sites, and even the most creatively designed websites, have a small palette of colors throughout the site. Making them predefined in what is almost like an index for the CSS makes it simple to reference and implement. Developers new to the code base and project do not need to go far to discover the colors needed to use.
This approach simplifies updates during redesigns or when addressing color contrast issues for accessibility. By modifying the central “index,” developers can propagate changes across large websites effortlessly, reducing errors in managing colors across hundreds or thousands of lines of code.

These variables are not limited to colors, but this is a great use case for custom properties. Font sizes and animations come to mind as other useful implementations.
Example of responsive design with CSS variables:
@media (min-width: 768px) { :root { –font-size: 18px; }}
Define animation timing or easing functions for consistent, reusable animations:
–animation-duration: 300ms; transition: all var(–animation-duration) ease-in-out;
Include a fallback color for older browsers:
color: var(–text-color, black);
Custom properties worked well in the implimentation of a light mode/dark mode toggle button I added to the family tree website with React context. The button basically switched the chosen :root css for light or dark and changed the colors across all the components in the application.
This is a fairly simple but useful demonstration of custom properties in CSS. If you want to learn more about CSS variables or custom properties visit: MDN Web Docs
Leave a Reply