NPH
Huy Nguyenhuynp.dev
Cover
CSS Tricks

The Future of CSS Variables

Author
Huy Nguyen
May 28, 20244 min

CSS Variables, officially known as Custom Properties, have been around for a while, but their potential is only just beginning to be tapped. Unlike preprocessor variables (Sass/Less), CSS variables are part of the DOM, meaning they can be manipulated with JavaScript and respect the cascade.

Why they matter

The ability to update a single value and have it propagate throughout your entire application instantly is a game changer for dynamic theming.

--primary-color: #6366f1

The Syntax

Defining a variable is simple. It usually happens in the :root pseudo-class for global scope. Notice how clean the syntax is in a modern codebase:

css
:root {
  /* Design Tokens */
  --primary-color: #6366f1;
  --spacing-unit: 16px;
  --font-stack: 'Inter', sans-serif;
}

.button {
  background-color: var(--primary-color);
  padding: var(--spacing-unit);
  font-family: var(--font-stack);
  transition: transform 0.2s ease;
}

.button:hover {
  transform: translateY(-2px);
  filter: brightness(110%);
}

JavaScript Interaction

You can access and modify these variables at runtime, which is impossible with Sass variables.

javascript
// Get the computed style
const root = document.documentElement;
const color = getComputedStyle(root).getPropertyValue('--primary-color');

// Set a new value dynamically based on user input
function updateTheme(newColor) {
  root.style.setProperty('--primary-color', newColor);
}

Conclusion

As browser support is now universal, there is no reason not to use CSS variables in your next project. They are the backbone of modern design systems.

Related articles

Enjoyed this article?

Subscribe to the newsletter to get notified about new posts.