0% completed
The var()
function enables you to use custom property values (CSS variables) in your styles. This makes it easier to manage and update your design by defining values in one place and reusing them throughout your CSS. With var()
, you can create themes, manage colors, and ensure consistency across your website.
/* Define a custom property */ :root { --property-name: value; } /* Use the custom property */ selector { property: var(--property-name); } /* With fallback value */ selector { property: var(--property-name, fallback-value); }
Explanation:
--
prefix (e.g., --main-color: #0077cc;
).:root
selector so they are globally available.var(--property-name)
function is used to retrieve the value of a custom property.In this example, we define a custom color variable in the :root
and apply it to a container as a background color.
Explanation:
--main-bg-color
and --main-text-color
are declared in the :root
, making them available globally..box
uses var(--main-bg-color)
and var(--main-text-color)
to apply the defined colors.In this example, we use a fallback value with the var()
function. If the custom property isn’t defined, the fallback value is used instead.
Explanation:
.fallback-box
uses var(--secondary-color, #4caf50)
for its background color.--secondary-color
is not defined, the fallback #4caf50
is used.Using the var()
function, you can make your CSS more efficient and responsive to change, making it easier to implement global style updates and maintain a consistent design system.
.....
.....
.....