Variables in CSS, also known as CSS custom properties, can be very useful for reducing duplication in CSS codes. They can be used to define a specific value once and then referenced in multiple places throughout the CSS file.
Using CSS variables involves two steps: defining the variable and using the variable.
First, let’s define some variables:
```
:root {
—main-color: #999999;
—accent-color: #ff5800;
}
```
In this example, `—main-color` and `—accent-color` are the variable names and the hex codes are the variable values.
Variables are usually declared inside the `:root` selector, which makes the variable globally available. But they can also be declared inside specific selectors to make them available only within that selector.
Now, let’s use these variables in our styles:
```
body {
background-color: var(—main-color);
}
a {
color: var(—accent-color);
}
```
In these examples, `var(—main-color)` and `var(—accent-color)` are using the variables we defined earlier.
Just replace the property value with `var(—variable-name)` to use the variable. The browser will automatically substitute the variable name with the variable value when rendering the CSS.
Please note that CSS variables are case sensitive so `—main-color` is different from `—Main-Color`.
CSS variables can be very helpful when we want to make our code cleaner and easier to manage, especially for large stylesheets or when we want to create themes.