The var() Function

The var() function in CSS allows you to access the value of a custom property (CSS variable). This helps maintain consistency and enables reuse of values throughout your stylesheets, simplifying updates and reducing errors.

Key Topics

Defining Variables

CSS variables are defined with the -- prefix and are usually declared inside the :root pseudo-class for global scope. Variables can also be scoped to specific selectors.

<style>
        :root {
            --primary-color: #007BFF;
            --secondary-color: #28A745;
            --padding-size: 15px;
        }
</style>

Explanation: The :root selector defines global variables that can be accessed throughout the stylesheet. These variables represent commonly reused values like colors and padding.

Using the var() Function

The var() function is used to retrieve the value of a CSS variable and apply it to a property.

<style>
        :root {
            --primary-color: #007BFF;
            --padding-size: 15px;
        }
        .button {
            background-color: var(--primary-color);
            padding: var(--padding-size);
            color: white;
            border: none;
            border-radius: 4px;
        }
</style>
<button class="button">Styled Button</button>

Explanation: The var() function applies the values of --primary-color and --padding-size to style the button, ensuring consistency and easier updates.

Fallback Values

The var() function supports a fallback value, which is used if the variable is not defined.

<style>
        .fallback-example {
            background-color: var(--undefined-color, #FF5733);
            padding: var(--undefined-padding, 20px);
            color: white;
            border-radius: 4px;
        }
</style>
<div class="fallback-example">This uses fallback values.</div>

Explanation: If a variable is not defined (e.g., --undefined-color), the fallback value provided (e.g., #FF5733) is used instead.

Key Takeaways

  • Global Variables: Use the :root pseudo-class to define global CSS variables.
  • Scoped Variables: Variables can also be scoped to specific selectors for localized effects.
  • var() Function: Use the var() function to access and apply variable values.
  • Fallbacks: Provide fallback values for variables to ensure graceful degradation when a variable is not defined.
  • Maintainability: CSS variables improve maintainability and consistency in your stylesheets.