CSS for Web Development

0% completed

Previous
Next
CSS var() Function

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.

Syntax

/* 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:

  • Defining Variables:
    • Variables are defined using the -- prefix (e.g., --main-color: #0077cc;).
    • It's common to define them in the :root selector so they are globally available.
  • Using Variables:
    • The var(--property-name) function is used to retrieve the value of a custom property.
    • Optionally, a fallback value can be provided if the variable is not set.

Example 1: Basic Usage of CSS Variables

In this example, we define a custom color variable in the :root and apply it to a container as a background color.

HTML

. . . .

Explanation:

  • Variable Definition:
    • --main-bg-color and --main-text-color are declared in the :root, making them available globally.
  • Using var():
    • The .box uses var(--main-bg-color) and var(--main-text-color) to apply the defined colors.
  • Outcome:
    • The box displays a consistent color scheme that can be easily updated by changing the variables.

Example 2: Using Fallback Values with CSS var()

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.

HTML

. . . .

Explanation:

  • Fallback Mechanism:
    • The .fallback-box uses var(--secondary-color, #4caf50) for its background color.
    • Since --secondary-color is not defined, the fallback #4caf50 is used.
  • Outcome:
    • The box maintains its styling even if a custom property is missing, making your design more robust and adaptable.

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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next