CSS Custom Properties (CSS Variables)

Roberto Moreno Celta
2 min readApr 19, 2023

--

https://www.google.com/search?q=css+variables&rlz=1C1GCEA_enAR1026AR1026&source=lnms&tbm=isch&sa=X&ved=2ahUKEwiN_sSH1LX-AhVmrJUCHVL9BkYQ_AUoAXoECAEQAw&biw=1280&bih=601&dpr=1.5#imgrc=k4qktSe6Oj0ruM

CSS variables, also known as CSS custom properties, allow developers to define a value once and reuse it throughout a CSS document. This feature simplifies code maintenance and promotes consistency across an application’s styling. In this article, we will explore the usage of CSS variables using the official Mozilla Developer Network (MDN) documentation as an example.

The MDN documentation explains that CSS variables are declared using the “ — “ prefix followed by the variable name and its value. For example, to declare a variable that represents a primary color, we could use the following code:

:root {
--primary-color: #007bff;
}

The :root pseudo-class targets the document's root element, making the variable available to all elements in the document. We can then reference the variable using the var() function, like this:

a {
color: var(--primary-color);
}

The var() function retrieves the value of the --primary-color variable and applies it to the color property of the a element. If we later decide to change the primary color, we can do so by updating the variable's value in a single location, and the change will propagate throughout the document.

The MDN documentation provides several examples of how to use CSS variables in practice. One example shows how to use variables to define a responsive layout with a flexible number of columns:

:root {
--columns: 3;
--column-width: calc(100% / var(--columns));
}

.grid {
display: flex;
flex-wrap: wrap;
}

.grid > * {
width: var(--column-width);
}

In this example, we declare two variables for the background color and text color, respectively. We then define a body.dark-mode selector that overrides the variable values for the dark mode theme. Finally, we apply the variable values to the background-color and color properties of the body element, which allows the theme to be toggled by adding or removing the dark-mode class from the body element.

In conclusion, CSS variables are a powerful feature that can help developers write more maintainable and consistent CSS code. By declaring variables and reusing them throughout a document, we can avoid repetition and make it easier to update the styling of an application. The MDN documentation provides many more examples of how to use CSS variables in practice, and I encourage readers to explore them further to unlock the full potential of this feature.

--

--

Roberto Moreno Celta

UX Designer & Front End Dev. Love for food, movies and video games.