Detailed Explanation of CSS Variables (Custom Properties)

Detailed Explanation of CSS Variables (Custom Properties)

I. What are CSS Variables
CSS variables (official name: custom properties) are entities in CSS used to store reusable values, defined with the -- prefix. They allow you to manage repeated values in one place and reference them throughout the document via the var() function.

II. Basic Syntax and Usage

  1. Defining variables:
/* Define global variables in the root element */
:root {
  --primary-color: #007bff;
  --spacing-unit: 16px;
  --main-font: "Arial", sans-serif;
}

/* Define local variables within specific elements */
.container {
  --border-radius: 8px;
}
  1. Using variables:
.button {
  background-color: var(--primary-color);
  padding: var(--spacing-unit);
  border-radius: var(--border-radius, 4px); /* The second parameter is a fallback value */
}

III. Core Features of CSS Variables

  1. Scoping Rules:

    • Global variables are defined in :root and accessible to all elements
    • Local variables are defined within specific selectors and accessible only to that element and its children
    .theme-dark {
      --bg-color: #333;
      --text-color: white;
    }
    
    .theme-light {
      --bg-color: white;
      --text-color: #333;
    }
    
  2. Inheritance:

    • Variables follow CSS inheritance rules
    • Child elements inherit variable values defined in parent elements
  3. Fallback Value Handling:

    /* If --secondary-color is undefined, use #ccc */
    color: var(--secondary-color, #ccc);
    
    /* Multi-layer fallback values */
    color: var(--undefined-var, var(--fallback-var, red));
    

V. Practical Application Examples

  1. Theme Switching:
:root {
  --primary: blue;
  --background: white;
}

[data-theme="dark"] {
  --primary: lightblue;
  --background: black;
}

body {
  background: var(--background);
  color: var(--primary);
  transition: all 0.3s ease; /* Add transition effect */
}
  1. Responsive Spacing System:
:root {
  --spacing: 8px;
}

@media (min-width: 768px) {
  :root {
    --spacing: 16px;
  }
}

.card {
  margin: calc(var(--spacing) * 2);
  padding: var(--spacing);
}

VI. Best Practices and Considerations

  1. Naming conventions: Use meaningful names, such as --header-height instead of --hh
  2. Unit handling: Include units when defining variables with units, and reference directly when using
  3. Browser support detection:
@supports (--css: variables) {
  /* Styles for browsers supporting CSS variables */
}
  1. Differences from preprocessor variables:
    • CSS variables are runtime and can be dynamically modified in JavaScript
    • Preprocessor variables are replaced with fixed values at compile time