The var() function in CSS is a powerful feature that enables developers to define and use custom CSS variables. It is also known as custom properties.
This function enhances code maintainability and flexibility by allowing the reuse of values throughout a stylesheet, making it easier to update styles across multiple elements from a single location.
To use the var()
function, you first need to define a custom property (global variable) using the --
prefix followed by a name and value pair, like so:
Define Custom Property Name and Value
:root { --primary-color: #007bff; }
In this example, --primary-color
is a custom property set to the hex color #007bff
. The :root
pseudo-class is used to declare global CSS variables that can be accessed anywhere within the document.
Let’s now see how you can use the var() function in CSS code.
Using var() Function
Once defined the custom property, you can use the var()
function to reference the custom property’s value in other CSS declarations, like this:
button { background-color: var(--primary-color); }
Here, the background-color
property of the button
element is set to the value of --primary-color
, which is #007bff
. This allows you to maintain consistency across your stylesheets and easily update the primary color of buttons by modifying the value of --primary-color
in one place.
Callback in var() Function
Furthermore, the var()
function supports fallback values, ensuring compatibility with browsers that do not support CSS variables. See the following example of handling callback.
button { color: var(--text-color, #333); }
In this case, if --text-color
is not defined, the button’s text color defaults to #333
. This fallback mechanism provides graceful degradation for older browsers.
The var()
function is not limited to color values; it can be used with any CSS property, including dimensions, fonts, and box shadows.
More Tricks
FAQs
The var() function in CSS allows developers to define and use custom properties, enhancing code maintainability and flexibility.
Fallback values can be specified within var() functions to ensure compatibility with browsers that do not support CSS variables, providing graceful degradation in styling.