Theming Components with CSS Variables
Neat theme swapping example included
In this article we will:
- Create a card component that can be styled with CSS variables.
- Implement theme swapping with CSS variables.
Why CSS Variables?
The unique thing about CSS variables is that they allow for styling between component boundaries.
That means that variables set in the root component can be accessed by all its child components, all without touching the root component’s view encapsulation. This is especially useful for theming considerations.
CSS variables are being considered by the Angular Material team as the future of component theming.
Once CSS variables (custom properties) are available in all the browsers we support, we will explore how to take advantage of them to make theming even simpler.
They are also mentioned in the Angular Blog.
Community feedback is very important to us. We decided to keep ::ng-deep support until Custom Properties achieve broader acceptance, implementation, and validation from developers.
To showcase styling with CSS variables we will create a simple card component.
We want to give the consumers of the component an option to style card’s header and FAB.
In the next example, we replace the hard coded values with
var() function, passing in two CSS variables
var()function inserts the value of a custom property.
The consumers of the card component must provide the values for the
--accent custom properties.
In code, you can set the value of the CSS variables in a number of ways:
- in component’s HTML
- in component’s CSS
- in component’s class
DomSanitizerbecause Angular sanitizes CSS variables set by regular bindings.
Theme Swapping Example
Building on the previous section, we will create a theme swapping example.
app-root component, we will define multiple themes which will be exposed as CSS variables. We will also create a method that generates a random theme.
First, we define a
Theme interface and set a few themes in the
In the next example, we use
@HostBinding to bind the DOM’s style property to a string consisting of two CSS variables. Each variable has the value set based on the current theme.
Because we are binding the
app-root's style property, the CSS variables will be available for every single component in the entire app.
In this example we only style a single
app-card component, but in a real world scenario we could style hundreds of components with this one simple binding.
Next, we add a
randomTheme method that generates a theme with random hex values for the
And finally, we display buttons that allow us to pick a theme.
And that’s it! We have implemented simple theme swapping with CSS variables.