Generate CSS classes and variables from Angular Material Palette
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:
In order to change the color of elements, usually, we would do it like below: ๐
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? โฌ๏ธ
or even by using CSS variables? ๐
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:
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 ๐.
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:
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:
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 ๐: