Modern CSS
CSS Custom Properties
--variables, var()
💡 CSS variables ek "naming a value once, use it everywhere" system hai — jaise ek company apna brand color ek jagah define kare (variable), phir poori website (buttons, links, headers) usi ek naam ko reference kare — color change karna ho to sirf EK jagah update karo.
Custom properties (CSS variables) --name: value; se define hote hain (usually :root par, globally), aur var(--name) se use hote hain. SASS/LESS variables se BADA farq: CSS variables actually RUNTIME par live hain — JavaScript se change ho sakte hain, aur CSS cascade/inheritance follow karte hain (context ke hisaab se alag values ho sakti hain).
:root {
--primary-color: #3498db;
--spacing-unit: 8px;
--font-heading: 'Poppins', sans-serif;
}
.button {
background-color: var(--primary-color);
padding: calc(var(--spacing-unit) * 2);
font-family: var(--font-heading);
}
.button:hover {
background-color: var(--primary-color-dark, #2980b9);
/* Second argument = fallback agar variable defined na ho */
}🔧
CSS variables ek "naming a value once, use it everywhere" system hai — jaise ek company apna brand color ek jagah define kare (variable), phir poori website (buttons, links, headers) usi ek naam ko reference kare — color change karna ho to sirf EK jagah update karo.
1 / 6
⚡ झट से Recap
- --name: value = define, var(--name) = use
- Runtime-live hain — JavaScript se change ho sakte hain, cascade follow karte hain
- Dark mode, theming ke liye bahut powerful (SASS variables se better)
इस page में (2 subtopics)
CSS variables sirf :root (global) tak limited nahi hain — kisi bhi selector par define ho sakte hain, aur sirf uske andar (cascade se) available hote hain. Ye "scoped theming" ke liye powerful hai.
.dark-section {
--text-color: white;
--bg-color: #1a1a1a;
background: var(--bg-color);
color: var(--text-color);
}
.light-section {
--text-color: black;
--bg-color: white;
/* SAME variable naam, ALAG value, alag scope mein */
}Tip: Component-scoped variables (jaise .card { --card-padding: 20px; }) ek component ko "self-contained, configurable" banate hain — bina global namespace pollute kiye.
CSS variables JavaScript se directly read/write ho sakte hain — style.setProperty()/getPropertyValue() se, jo dynamic theming ya interactive effects (jaise mouse-position-based styling) enable karta hai.
// JavaScript se CSS variable set karna:
document.documentElement.style.setProperty('--primary-color', '#e74c3c');
// Poori CSS turant update ho jaati hai jaha bhi var(--primary-color) use hua hai
// Read karna:
const value = getComputedStyle(document.documentElement)
.getPropertyValue('--primary-color');Tip: Ye JavaScript-CSS variable interaction hi dark mode toggles, user-customizable themes, aur interactive design tools (jaise color pickers) ka foundation hai.