Custom properties in CSS (also called variables) allow you to store reusable values, such as colors, sizes or spacings, to use them in multiple places of the code.
If you change the value on a site, it gets updated in all places where it is used.

They are especially useful when working on large web projects like HTML or React, or using MUI, because they help you maintain visual consistency.
The variables are declared using two dashes at the beginning of the name:
--variable-name: value;
They are usually declared in the :root selector so that they are available globally throughout the document:
:root { --primary-color: #1976d2; --secondary-color: #ff9800; --base-spacing: 16px; --radio-border: 8px; }
:root represents the root element of the document (html), so it’s a good practice to define them there when you want them to be global.
To use a variable, the function var()
is used:
selector { property: var(--variable-name); }
PRACTICAL EXAMPLE:
body { background-color: var(--primary-color); padding: var(--base-spacing); } .card { border-radius: var(--border-radius); background-color: var(--secondary-color); }
If you change the value of --primary-color in :root tomorrow, the entire design will automatically change.
You can define an alternative value if the variable doesn’t exist:
color: var(--color-text, black);
If --color-text isn’t defined, black will be used.
CSS variables respect the scope.No always need to be in :root. You can define them inside a specific selector.
Ejemplo:
.card { --color-fondo: #f5f5f5; background-color: var(--color-fondo); }
Aquí --color-fondo solo existe dentro de .card y sus hijos.
This is powerful for creating components with encapsulated styles.
You can redefine variables to change themes or modes (very useful for dark mode).
Example:
:root { --color-fondo: white; --color-texto: black; } .dark-mode { --color-fondo: #121212; --color-texto: white; } body { background-color: var(--color-fondo); color: var(--color-texto); }
If you add the dark-mode class to the body, all colors change automatically.
You can modify variables from JavaScript:
document.documentElement.style.setProperty('--color-principal', '#4caf50');
This is useful if you want to change the theme based on a user action.
Use clear and consistent names
Ejemplo:
–color-primary
–spacing-md
–border-radius-lg
Agrupa por categorías si el proyecto es grande
:root { /* Colores */ --color-primary: #1976d2; --color-danger: #d32f2f; /* Espaciados */ --spacing-sm: 8px; --spacing-md: 16px; /* Bordes */ --radius-md: 8px; }
No abuses de variables para valores que solo se usan una vez.
