Skip to main content

CSS Variables

CSS variables allow you to store values that you can reuse throughout your stylesheet. They are scoped to the element they are declared on, and they inherit their values, much like other CSS properties.

Syntax

To define a CSS variable, you use two dashes (--) followed by the variable name, like so:

:root {
--primary-color: #3498db;
}

To use a CSS variable, you reference it with the var() function:

button {
background-color: var(--primary-color);
}

Examples

  1. Basic Usage

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

    body {
    font-size: var(--font-size);
    font-family: var(--font-family);
    }
  2. Scoped Variables

    Variables can be scoped to specific elements:

    .dark-theme {
    --primary-color: #000;
    }

    .light-theme {
    --primary-color: #fff;
    }

    button {
    background-color: var(--primary-color);
    }
  3. Fallback Values

    You can provide a fallback value in case the variable is not defined:

    button {
    background-color: var(--primary-color, blue);
    }
  4. Dynamic Changes with JavaScript

    You can dynamically change the value of a CSS variable using JavaScript:

    document.documentElement.style.setProperty('--primary-color', 'red');

Best Practices

  • Global Scope: Define variables that are used globally in the :root selector for easy access and maintainability.

  • Semantic Naming: Use semantic names for your variables to make it clear what they represent, e.g., --button-bg-color instead of --bgc.

  • Fallbacks: Always provide a fallback value for better browser compatibility and to prevent unexpected behaviors.

  • Theming: Use variables to easily switch between different themes in your application.

  • Debugging: Browser developer tools now support inspecting CSS variables, making it easier to debug and fine-tune them.

CSS variables offer a level of abstraction and reusability that can make your stylesheets more organized and easier to manage, which is invaluable in large-scale projects or design systems.