Generate CSS classes and variables from Angular Material Palette

Vugar Abdullayev
3 min readMay 1, 2022

--

Background photo by Tim Swaan on Unsplash

Not a member of Medium? Read this article for free here.

In this blog, we should learn about generating CSS classes and variables from Angular Material Palette. It can also be used to strengthen some SCSS skills.

โœ… Generate CSS classes from Angular Material Palette

โœ… Generate CSS variables from Angular Material Palette

๐Ÿ—Ž Source Code: https://github.com/vugar005/youtube-webapp-turborepo

๐Ÿ’Ž Live Demo: https://youtube.vugar.app

Why?๐Ÿค”

Letโ€™s say we have some HTML elements like this:

Html elements for styling.

In order to change the color of elements, usually, we would do it like below: ๐Ÿ˜•

Usual and not convenient way to style elements.

Well as you see, it is already verbose ๐Ÿ˜•. Just for adding color, we have to import the palette and use a map-get function.

Solution: ๐Ÿ› 

What if we would able to style HTML elements just by adding classes like the below? โฌ‡๏ธ

Add colors using CSS classes

or even by using CSS variables? ๐Ÿ™‚

Add colors using CSS classes

In order to achieve this, we can generate CSS classes and CSS variables from Angular Material Palette. The palette is actually a SCSS map which is like a Map object in Javascript.

Assume we have a palette like the below:

Sample palette

So letโ€™s add a new file called generate-material-classes.scss which would include the below code.

Note: we are going to simplify below code later in this post ๐Ÿš€.

Generate angular material classes version 1

Basically, we iterate over key/values for each palette and add CSS classes. We also append those key/values to an array which we use for root to generate CSS variables.

Now in styles.scss file:

@import 'generate-material-colors';@include generate-material-classes();

Now we can use classes like app-primary-60 and so on.

Also, letโ€™s confirm the solution by inspecting CSS variables via devTools:

Generated CSS variables

Beautiful, is not it? ๐Ÿ˜Ž

Optimized solution: ๐Ÿš€

As you see we add 3 different mixins for generating primary, accent, and warning colors in the above solution ๐Ÿ˜•. So letโ€™s simplify this by using a single function with parameters:

Generate angular material classes and CSS variables: optimized version

Thatโ€™s all hope you enjoyed it and found it useful. Thanks for reading.๐Ÿ

๐Ÿ—Ž Source Code: https://github.com/vugar005/youtube-webapp-turborepo

About me: I am a junior front-end developer.

Twitter: https://twitter.com/Vugar005

You can also check out my other blogs or projects ๐Ÿ’Ž:

--

--