🎨 CSS Variables & Custom Properties

Last Updated: November 2025


CSS Variables, also called Custom Properties, allow you to store values (like colors, sizes, fonts) in reusable names.
They make your CSS cleaner, dynamic, and easier to maintain.

🗣 Hinglish Tip: Socho variables ek dabba (box) jaise hain — jisme tum color, size, ya koi value rakh ke kahin bhi use kar sakte ho!

Syntax

Always start a variable name with --

:root {
  --main-color: #ff5733;
  --padding-size: 10px;
}

Use :root to make it global (accessible anywhere)

Then use it like this 👇

button {
  background-color: var(--main-color);
  padding: var(--padding-size);
}

var(--variable-name) is used to apply a CSS variable.


Color Theme

:root {
  --bg-color: #f5f5f5;
  --text-color: #222;
  --highlight: #ff6f61;
}

body {
  background: var(--bg-color);
  color: var(--text-color);
}

button {
  background: var(--highlight);
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
}

If you change --highlight, every button color updates automatically.

Dark Mode Toggle

:root {
  --bg: #ffffff;
  --text: #111111;
}

[data-theme="dark"] {
  --bg: #111111;
  --text: #ffffff;
}

body {
  background: var(--bg);
  color: var(--text);
}

Switching data-theme="dark" dynamically changes theme colors.

🗣 Hinglish Tip: “Ek hi CSS me light aur dark dono theme handle kar sakte ho!”


⚙️ Variable Scope

  • Global Defined in :root Everywhere
  • Local Defined in element That element & children only
:root {
  --main-color: red;
}

.card {
  --main-color: blue;
  color: var(--main-color);
}

Inside .card, color = blue (local variable overrides global).


🧩 Fallback Values

You can define a fallback if the variable doesn’t exist.

p {
  color: var(--secondary-color, gray);
}

If --secondary-color is undefined → uses gray.

Dynamic Spacing

:root {
  --gap: 20px;
}

.container {
  display: flex;
  gap: var(--gap);
}

Change --gap value to adjust spacing site-wide.