Using CSS Custom Properties with Angular
CSS Custom Properties are native, runtime CSS variables. They can be scoped to a sub-tree of the DOM, such as Angular's element injector hierarchy. We are used to doing this with CSS classes with increased specificity or CSS source ordering.
CSS Custom Properties do not rely on specificity or CSS source ordering. Instead, we can dynamically change the value at runtime or override it for a specific part of the DOM.
Let's look at a simple example. Here, we have listed both a global and a scoped declaration of the --background-color
CSS custom property:
:root { --background-color: rebeccapurple; } .contrast { --background-color: hotpink; } .panel { background-color: var(--background-color); }
Now, look at the following HTML and try to reason about the global and scoped CSS Custom Properties. Don't worry if you do not understand it immediately. We will discuss it in detail in a moment...