Custom Properties in CSS


CSS Custom Properties are variables that we can define at the stylesheet level and assign values to them. They start with two hyphens and are declared within the scope of the root element, which means their values can be inherited by descendant elements. This allows us to create a single variable and use it in multiple places, significantly reducing repetitive CSS code.

Example of declaration


Why should we use CSS Custom Properties?

  1. Easy Customization: With CSS Custom Properties, we can change the appearance of our webpage simply by altering the variable values, without the need to edit multiple CSS rules.
  2. Simplicity and Code Readability: Utilizing CSS variables makes our code more understandable and easier to maintain.
  3. Responsiveness: CSS Custom Properties allow us to adjust styles based on various factors, such as screen size or user preferences.
  4. Animations and Transitions: We can use CSS Custom Properties to smoothly change values over time, enabling us to create engaging animations and transitions.
  5. Team Collaboration: CSS variables facilitate collaboration among team members by introducing consistency in styles and enhancing project scalability.

How to use CSS Custom Properties?

To use CSS variables, we simply employ the var() function in relevant parts of our CSS code. Here’s a simple example of how to use previously defined variables:


The value var(--primary-color) will be replaced with the value defined earlier in :root.