Learn the concept
CSS Custom Properties (Variables)
CSS custom properties (--my-var) are native CSS variables that cascade, can be scoped to selectors, updated at runtime with JavaScript, and inherited by child elements. Sass variables ($my-var) are compile-time only and produce static output. CSS variables enable theming, dark mode, and dynamic styling without preprocessors.
CSS Custom Properties:\n- Declared with -- prefix: --color-primary: #3b82f6\n- Used with var(): color: var(--color-primary)\n- Cascade and inherit like regular CSS properties\n- Can be scoped to any selector\n- Can be updated at runtime with JavaScript\n- Support fallback values: var(--color, #000)\n\nvs Sass Variables:\n| Feature | CSS Variables | Sass Variables |\n|---------|---------------|---------------|\n| Runtime | Yes (dynamic) | No (compile-time) |\n| Cascade | Yes | No |\n| Scope | Any selector | Block scope |\n| JS access | Yes | No |\n| Media queries | Yes | No |\n| Browser support | Modern browsers | Any (compiles to CSS) |\n\nUse cases:\n- Theming (light/dark mode)\n- Component variants\n- Responsive values via media queries\n- JavaScript-driven dynamic styles
/* Define variables on :root (global) */
:root {
--color-primary: #3b82f6;
--color-bg: #ffffff;
--color-text: #111827;
--spacing-md: 1rem;
--radius: 8px;
}
/* Dark mode override */
[data-theme="dark"] {
--color-primary: #60a5fa;
--color-bg: #111827;
--color-text: #f9fafb;
}
/* Usage */
.card {
background: var(--color-bg);
color: var(--color-text);
border-radius: var(--radius);
padding: var(--spacing-md);
}
.button {
background: var(--color-primary);
/* Fallback value */
border-color: var(--border-color, transparent);
}Allowing users to switch between light and dark modes, or choose from a palette of primary colors, by simply changing a few CSS variable values.
Where components can adapt their styling (e.g., spacing, colors, font sizes) based on parent-defined CSS variables, providing flexibility and consistency.
By defining scale factors or base units in CSS variables that can be dynamically updated via JavaScript or media queries to create a harmonious design system.
Build a web page with a button that toggles between light and dark themes using CSS custom properties.
Create a flexible card component whose padding, border-radius, and colors are controlled by CSS variables, demonstrating easy customization.
Modern versions of Bootstrap extensively use CSS custom properties for theming, allowing developers to easily customize default styles without overriding complex Sass variables and recompiling.
Google's Material Design system often leverages CSS variables to define and manage a consistent set of design tokens (colors, typography, spacing) across its components and applications.