CSS Custom Properties act like variables in your CSS, allowing you to store specific values for reuse throughout your website. They begin with --
followed by a chosen name, and you can assign them a value using the var() function. Once defined, these properties can be utilized anywhere in your CSS code.
CSS Custom Properties
For instance, if you want to establish a custom property for your website's primary color, you can define it as follows:
:root {
--primary-color: #007bff;
}
In this snippet, :root targets the root element (usually <html>
), and --primary-color is the name of your custom property. The value #007bff
represents a specific shade of blue.
You can then apply this custom property in your CSS rules like this:
.header {
background-color: var(--primary-color);
}
.button{
color: var(--primary-color);
border: 2px solid var(--primary-color);
}
In this example, the --primary-color custom property is applied as the background color for the .header
class, as well as the text color and border color for the .button
class.
If you decide to change the value of --primary-color, for instance, to a different shade of blue or an entirely different color, the change will automatically reflect everywhere this custom property is used in your stylesheets.
CSS Custom Properties simplify the management of frequently used values by centralizing them. This approach enhances the flexibility, organization, and maintainability of your CSS code.