CSS variables or custom properties are one of the best new features of CSS that allow web designers to define global values, which can be utilized anywhere in their CSS code where needed. This functionality also makes it much easier to manage and change those values, reducing code duplication.
In general, using CSS variables grants web designers a special flexibility and greater customization. To start using them, it's enough to understand how to define these variables and then have access to them.
Before anything else, you should know that CSS variables can only be used in a limited scope, which are defined. For this reason, you should carefully select their defining regions. The best practice for using them is essentially in :root, so all components can benefit from them.
As an example, suppose you want to define a primary color for the entire site. You could accomplish this with a CSS variable and simply refer to that variable wherever it's needed.
Below is a simple example of how to define and use CSS variables. This example can help you utilize CSS variables in your own web projects.
I hope with these initial explanations, you will easily utilize this powerful capability in your website design and development and benefit from its advantages.
:root {
--main-color: #ff6347;
--secondary-color: #4caf50;
--font-stack: 'Helvetica Neue', sans-serif;
}
body {
font-family: var(--font-stack);
color: var(--main-color);
}
button {
background-color: var(--secondary-color);
color: #fff;
border: none;
padding: 10px 15px;
}
The following line indicates how to define the variables using :root. The code --main-color
is a CSS variable that has been assigned to the primary color of the site. The code --secondary-color
is another variable for secondary colors. The code --font-stack
is for defining the default font.
In another part of CSS, we can easily use the variables using the var()
function. The code
font-family: var(--font-stack);
in body
sets the font using the defined variable.
The variable --main-color
is used for the main text color.
The variable --secondary-color
is used for secondary elements which can be specified in the background.