28csscustomproperties

CSS Custom Properties

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.

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.

Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.

top-home