CSS Custom Properties, also known as CSS variables, are a powerful tool in CSS that allow you to define a value once and reuse it throughout your stylesheet.
This can greatly simplify your code and make it easier to maintain.
To define a custom property, you use the `–` prefix followed by a name and a value.
For example:
css
:root {
--primary-color: #007bff;
}
This defines a custom property called `–primary-color` with a value of `#007bff`.
You can then use this custom property anywhere in your stylesheet by referencing it with the `var()` function.
For example:
css
a {
color: var(--primary-color);
}
This sets the color of all links to the value of `–primary-color`, which in this case is `#007bff`.
Custom properties can also be inherited and overridden just like any other CSS property.
For example:
css
.container {
--bg-color: #ffffff;
}
.card {
background-color: var(--bg-color);
}
.card-secondary {
--bg-color: #f8f9fa;
}
In this example, the `.container` class defines a custom property called `–bg-color` with a value of `#ffffff`.
The `.card` class then uses this custom property to set its background color.
However, the `.card-secondary` class overrides the value of `–bg-color` with a new value of `#f8f9fa`, causing the background color of elements with this class to be different from those with just the `.card` class.
Overall, CSS Custom Properties are a powerful tool that can greatly simplify your code and make it easier to maintain.