#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 16 of 49easy

What are CSS Custom Properties?

Understanding CSS variables and their usage.

What You'll Learn

  • Declaring variables
  • Using variables
  • Scope and fallbacks

Declaring Variables

styles.cssCSS
:root {
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --spacing: 16px;
  --font-size-base: 16px;
}

Using Variables

styles.cssCSS
.button {
  background-color: var(--primary-color);
  padding: var(--spacing);
  font-size: var(--font-size-base);
}

/* With fallback */
.element {
  color: var(--text-color, black);
}

Scope

styles.cssCSS
:root {
  --color: blue; /* Global */
}

.card {
  --color: red; /* Local to .card */
}

.card p {
  color: var(--color); /* Uses red */
}

Dynamic Updates

code.jsJavaScript
// Change via JavaScript
document.documentElement.style.setProperty('--primary-color', 'red');