CSS Variables (Custom Properties)

Using CSS Custom Properties

CSS variables (custom properties) allow you to store values that you can reuse throughout your stylesheet.

They make your CSS more maintainable and enable dynamic theming.

/* Define Variables */
:root {
  --primary-color: #d1039e;
  --secondary-color: #7a0060;
  --font-size: 16px;
  --spacing: 20px;
  --border-radius: 8px;
}

/* Use Variables */
.button {
  background: var(--primary-color);
  font-size: var(--font-size);
  padding: var(--spacing);
  border-radius: var(--border-radius);
}

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

/* Local Scope */
.card {
  --card-padding: 30px;
  padding: var(--card-padding);
}
  • --variable-name - Define custom property
  • var(--variable-name) - Use custom property
  • var(--name, fallback) - Provide fallback value
  • :root - Global scope for variables
  • Can be changed with JavaScript
  • Cascade and inherit like regular properties

Try CSS Variables

<div class="theme-demo">
  <div class="card primary">Primary Card</div>
  <div class="card secondary">Secondary Card</div>
  <button class="btn">Button</button>
</div>

Note: CSS variables can be changed dynamically with JavaScript, making them perfect for theme switching!