CSS Variables


🔹 What Are CSS Variables?

CSS Variables, also known as custom properties, are entities defined by authors that contain specific values to be reused throughout a document.

They help make styles more maintainable, reusable, and easier to update.


🔸 Syntax

:root {
  --main-color: #3498db;
  --font-size: 18px;
}
Usage:
h1 {
  color: var(--main-color);
  font-size: var(--font-size);
}
  • Variables start with --

  • Access them using var(--variable-name)

  • Declare them inside :root for global access


🔸 Scope of Variables

1. Global Scope
:root {
  --bg-color: #fff;
}

Accessible from anywhere in the CSS.

2. Local Scope
.card {
  --padding: 20px;
  padding: var(--padding);
}

Only accessible within .card and its children.


🔸 Fallback Values

color: var(--primary-color, blue);

If --primary-color is not defined, blue will be used.


🔸 Updating Variables with JavaScript

document.documentElement.style.setProperty('--main-color', 'red');

CSS variables are dynamic and can be changed via JavaScript at runtime.


🔸 Benefits of CSS Variables

  • Reusability

  • Centralized control

  • Easy theme management (light/dark modes)

  • JavaScript-friendly


🔸 Example: Light and Dark Theme

:root {
  --bg-color: #ffffff;
  --text-color: #000000;
}

.dark-theme {
  --bg-color: #000000;
  --text-color: #ffffff;
}

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

Switch .dark-theme class to activate dark mode.


Practice Questions

Q1. Create a variable for primary color and apply it to headings.

Q2. Define a --radius and use it for button border-radius.

Q3. Use --font-base for font size of all paragraphs.

Q4. Add --box-shadow for cards and apply it.

Q5. Define a fallback for an undefined variable.

Q6. Set --container-width and use it in a .container class.

Q7. Change --main-color dynamically using JavaScript.

Q8. Create light and dark themes using CSS variables.

Q9. Apply --gap between grid columns.

Q10. Make a reusable --transition-speed variable and apply it to links.


Go Back Top