Generate CSS classes and variables from Angular Material Palette
--
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 💎: