CSS variables or custom properties: how they work

CSS variables or custom properties: how they work

CSS variables, also called "custom properties", are a powerful tool that allows you to define a value and reuse it within a style sheet.

CSS variables, also called "custom properties", are a powerful tool that allows you to define a value and reuse it within a style sheet. This allows you to create cleaner, more modular, and easier to use CSS code maintain.

CSS variables are defined using the syntax --variable-name and can be used anywhere in the style sheet, even inside other variables. To define a variable, you need to use the following syntax:


:root {
	--variable-name: value;
}
	

The :root selector is used to define the variable globally, making it available throughout our CSS code.

Once the variable is defined, you can use it within any CSS rule, using the following syntax:


selector {
	property: var(--variable-name);
}
	

For example, if you want to use a variable to define the background color of an element, you can define the variable as follows:


:root {
	--bg: #f0f0f0;
}
	

and use it inside the CSS rule:


#site-header {
	background-color: var(--bg);
}
	

CSS variables can also be used within Media Queries and advanced selections. Also, you can set a default value for the variable using the following syntax:


property: var(--variable-name, default-value);
	

This means that if the variable has not been defined, the default value will be used instead.

In summary, CSS variables are a useful tool for simplifying our CSS code, by making it cleaner and easy to maintain. They are used to define a value once and reuse it throughout the code. This allows you to make global changes to a website or app, without having to manually edit each CSS rule.