CSS Variables – The var() Function

CSS variables, also known as custom properties, allow you to store reusable values in your stylesheets. The var() function is used to access and apply these variables. This feature makes managing and maintaining CSS easier, especially for large projects, as you can centralize values like colors, fonts, and spacing.

Why Use CSS Variables?

  1. Reusability: Define once, use multiple times.
  2. Consistency: Maintain a uniform design across your project.
  3. Flexibility: Update a single variable to change the design globally.
  4. Improved Maintainability: Centralized control for quicker edits and better readability.

Declaring CSS Variables

CSS variables are defined within a CSS rule using the -- prefix. They can be declared globally or locally.

Global Variables

Global variables are declared inside the :root pseudo-class, which represents the root element of the document.

Example:

:root {
    --primary-color: #007bff;
    --secondary-color: #6c757d;
    --font-size: 16px;
}

Local Variables

Local variables are declared within specific selectors and are only available within that scope.

Example:

.container {
    --padding: 20px;
    --background-color: #f8f9fa;
}

Using CSS Variables with var()

To use a CSS variable, apply the var() function, passing the variable name as the argument.

Example:

.button {
    background-color: var(--primary-color);
    color: #fff;
    padding: var(--padding, 10px); /* Default value of 10px */
    font-size: var(--font-size);
}

In the above example:

  • var(--primary-color) retrieves the value of the --primary-color variable.
  • Default Values: If a variable is not defined, the fallback value (e.g., 10px) is used.

Practical Use Cases

1. Theme Management

CSS variables make it easy to implement light and dark themes.

Example:

:root {
    --background-color: #ffffff;
    --text-color: #000000;
}

.dark-theme {
    --background-color: #000000;
    --text-color: #ffffff;
}

body {
    background-color: var(--background-color);
    color: var(--text-color);
}

Switching themes is as simple as adding the .dark-theme class to the root element.

2. Typography Control

Define font styles and reuse them across different elements.

Example:

:root {
    --font-family: Arial, sans-serif;
    --heading-size: 24px;
    --text-size: 16px;
}

h1 {
    font-family: var(--font-family);
    font-size: var(--heading-size);
}

p {
    font-family: var(--font-family);
    font-size: var(--text-size);
}

3. Dynamic Spacing

CSS variables are excellent for creating a consistent spacing system.

Example:

:root {
    --spacing-small: 8px;
    --spacing-medium: 16px;
    --spacing-large: 32px;
}

.container {
    padding: var(--spacing-medium);
    margin: var(--spacing-large);
}

.button {
    margin: var(--spacing-small);
}

4. Responsive Design

CSS variables can adapt to screen size using media queries.

Example:

:root {
    --font-size: 16px;
}

@media (max-width: 768px) {
    :root {
        --font-size: 14px;
    }
}

p {
    font-size: var(--font-size);
}

Browser Compatibility

CSS variables are supported in most modern browsers, but they are not supported in Internet Explorer. For older browsers, consider using fallbacks or preprocessing tools like SASS or LESS.

Limitations of CSS Variables

  1. No Conditional Logic: CSS variables cannot perform conditional checks like if or else.
  2. Cannot Be Used in Media Queries: Variables cannot directly replace media query values like breakpoints.
  3. Browser Compatibility: Limited support in older browsers (e.g., Internet Explorer).

Tips for Working with CSS Variables

  • Organize Variables: Keep your variables grouped and well-documented in the :root section for better maintainability.
  • Use Default Values: Always specify a fallback value in var() to handle undefined variables.
  • Combine with JavaScript: Dynamically update CSS variables using JavaScript for advanced functionality.

Updating CSS Variables with JavaScript

One of the most powerful aspects of CSS variables is that they can be manipulated dynamically with JavaScript.

Example:

<div class="theme-toggle">
    <button onclick="switchTheme()">Switch Theme</button>
</div>

<script>
    function switchTheme() {
        document.documentElement.style.setProperty('--primary-color', '#28a745');
    }
</script>

Conclusion

CSS variables and the var() function provide a powerful, flexible way to manage and maintain your styles. They streamline theming, improve consistency, and enable dynamic updates for modern web designs. By integrating CSS variables into your workflow, you can make your stylesheets cleaner, more maintainable, and scalable.

For more coding tips and tutorials, visit The Coding College—your go-to destination for mastering web development!

Leave a Comment