Topic 27 of 30
Custom Advanced
Overview
Advanced CSS custom properties techniques include component-scoped variables, JavaScript interaction, theme switching, responsive tokens, and cascading defaults — making CSS variables the backbone of design systems.
Syntax
css
/* Component-scoped overrides */
.btn { --btn-color: #FFD700; --btn-text: #000; }
.btn-danger { --btn-color: #EF4444; --btn-text: #fff; }
/* Use tokens with fallback */
.button {
background: var(--btn-color, gold);
color: var(--btn-text, #000);
}
/* Responsive tokens with clamp */
:root {
--space-fluid: clamp(1rem, 4vw, 2rem);
--font-fluid: clamp(1rem, 2.5vw, 1.25rem);
}
/* Theme via :root class toggle */
:root[data-theme="dark"] {
--bg: #0f0f0f;
--text: #f5f5f5;
}
:root[data-theme="light"] {
--bg: #ffffff;
--text: #1a1a1a;
}
/* JavaScript update */
document.documentElement.style.setProperty('--accent', '#FF6B6B');Common Pitfalls
- CSS variables cascade like any CSS property — a variable defined on a child overrides the parent's variable for that element and its descendants.
- CSS variables are case-sensitive — --Color is different from --color.
- Interview tip: Use the _ prefix convention (--_private) to mark internal component variables that shouldn't be overridden from outside.
Real-World Example
A component design system using CSS custom properties as component API:
example
css
/* Button component with customizable API */
.btn {
/* Default values */
--_bg: var(--btn-bg, #FFD700);
--_text: var(--btn-text, #000);
--_radius: var(--btn-radius, 8px);
--_padding: var(--btn-padding, 12px 24px);
--_shadow: var(--btn-shadow, 0 4px 12px rgba(255,215,0,0.3));
background: var(--_bg);
color: var(--_text);
border-radius: var(--_radius);
padding: var(--_padding);
box-shadow: var(--_shadow);
}
/* Customized without creating new classes */
.checkout-page .btn {
--btn-bg: #10B981;
--btn-radius: 999px; /* pill shape */
}
/* Alert component with semantic colors */
.alert { --_color: var(--alert-color, #FFD700); }
.alert-success { --alert-color: #10B981; }
.alert-error { --alert-color: #EF4444; }
.alert-info { --alert-color: #3B82F6; }