Ronalds Vilciņš


What are variables in CSS?

CSS variables, also known as CSS custom properties allow you to define values that can be reused throughout your stylesheet, making it easier to maintain and update your styles as your project evolves.

One of the main advantages of using CSS variables is that they can be modified dynamically, either through JavaScript or using the :root pseudo-class and the setProperty method. This means that you can change the values of your variables on the fly, allowing you to easily create responsive designs or customize your styles for different users or contexts.

To declare a CSS variable, you use the -- prefix followed by the name of your variable and the value you want to assign to it. For example:

:root {
  --primary-color: #333;
  --secondary-color: #999;

You can then use these variables in your styles by using the var() function. For example:

body {
  color: var(--primary-color);

a {
  color: var(--secondary-color);

One of the key benefits of using CSS variables is that they allow you to centralize your styles and make it easier to update them. For example, if you want to change the primary color of your site from #333 to #444, you can simply update the value of the --primary-color variable in your :root block, and all of the elements that use that variable will be updated automatically.

CSS variables also have a number of other useful features, such as the ability to set fallback values using the var() function, or to use them as part of complex calculations using the calc() function.

Overall, CSS variables are a powerful and flexible for managing styles in your web projects. They allow you to create modular and maintainable stylesheets, and make it easier to update and customize your designs as your project evolves.