CSS Variables, also known as custom properties, allow you to store reusable values and apply them dynamically. They make your styles more maintainable, scalable, and customizable.


1️⃣ Defining CSS Variables

:root {
  --primary-color: #3498db;
  --secondary-color: #e74c3c;
  --font-size: 16px;
}


2️⃣ Using CSS Variables

body {
  color: var(--primary-color);
  font-size: var(--font-size);
}

💡 Tip: If a variable is not defined, you can provide a fallback value:

p {
  color: var(--text-color, black); /* Uses black if --text-color is undefined */
}


3️⃣ Scoped CSS Variables

CSS variables can be scoped to specific elements. A locally defined variable will override the global variable inside that scope.

:root {
  --main-color: #3498db; /* Global variable */
}

div {
  --main-color: #e74c3c; /* Scoped only to div elements */
}

p {
  color: var(--main-color); /* Uses the closest defined --main-color */
}


4️⃣ Benefits of CSS Variables

Reusability → Define once, use everywhere.

Maintainability → Update a single value to update all related styles.