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
- 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;
}
- 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
-
Scoping Rules:
- Global variables are defined in
:rootand 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; } - Global variables are defined in
-
Inheritance:
- Variables follow CSS inheritance rules
- Child elements inherit variable values defined in parent elements
-
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
- 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 */
}
- 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
- Naming conventions: Use meaningful names, such as
--header-heightinstead of--hh - Unit handling: Include units when defining variables with units, and reference directly when using
- Browser support detection:
@supports (--css: variables) {
/* Styles for browsers supporting CSS variables */
}
- 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