Css variables are custom properties that are used to set values which are reusable in a webpage. These can be set globally or locally in a webpage. To set a value, you have to use this notation --color:#000000; in which the double hypens are very crucial and should be put into use.After setting the values, it is important to use the var() function which contains the variable values you have set.
Instead of repeating the same styles over and over again, you can use CSS variables to achieve consistency and modularity in your designs.
To use CSS variables, follow these steps:
Using CSS variables provides flexibility and modularity. You can define variables for colors, sizes, fonts, etc., making it easier to maintain and update your styles throughout the website
Use the `--` prefix followed by a name to define a CSS variable in the selector where you want to use it. For example
:root {
--primary-color: #eeeee;
}
Here, `--primary-color` is the name of the variable, and `#eeeee` is the value.
- Apply the CSS variable: Use the `var()` function to reference the CSS variable where you want to apply it. For example
.button {
background-color: var(--primary-color);
}
Here, the `var(--primary-color)` expression is used as the value for `background-color`
- Setting local variable ,
3. Update the CSS variable dynamically (optional): CSS variables can be changed dynamically using JavaScript. For example:
document.documentElement.style.setProperty('--primary-color', 'red');
This JavaScript code updates the value of the `--primary-color` variable to `red` on the `documentElement`.
Conclusion
CSS variables are a powerful tool for creating maintainable, efficient, and consistent website designs. By using variables to define and store values like colors, fonts, and layout styles, you can easily reuse them throughout your entire site.