What are CSS Custom Properties ?
In this article, we will learn about CSS custom properties & their implementation. CSS custom properties are also referred to as CSS variables or cascading variables. These entities contain specific values that will be reused in the entire document & can be accessed using the var() function (e.g., color:(–primary-color);). The property name which has a prefix as –, depicts the custom properties & their value will be used in other declarations using the var() function.
Generally, when we are styling a large website that may contain a huge amount of CSS properties & most probably we have used similar values multiple times. It is really hard to manage the large-size styling properties. In order to handle this, custom properties allow us to declare a variable in one place, can be referred to multiple other places. This will reduce the effort to manage the code because we can update values easily by making changes in a single place.
- For variable:
var( --custom-name, value )
Parameters: The var( ) function accepts two parameters which are listed below:
- –custom-name: It is a required parameter that accepts the custom property name.
- value: It is an optional parameter. It accepts a fallback value which is used when the custom property is invalid.
- For custom properties:
The value assigned to the custom property will be matched for any sequence of one or more tokens until the sequence breaks & does not contain any more valid tokens.
We will create some CSS variables & define the value of these CSS variables, use them to style the HTML components.
Example 1: In this example, we will create CSS variables for background color, primary font color, and heading property.
Example 2: In this example, we will use the box-shadow-color property to create the shadow effect while hovering on it.
First, we will define some styling properties for the dark theme and the light theme. By default, we set the theme of the container as dark. We will also use theme CSS custom properties to set the style for our HTML webpage elements.
- Google Chrome 49.0
- Microsoft Edge 15.0
- Firefox 31.0
- Safari 9.1
- opera 36.0