Using CSS Modules
I believe the key to learning fast is tackling basics first. CSS modules are files where all local class names are locally scoped for an individual component. That means all the class names will only apply to one component. But why?
Well, on my team we faced a problem that other teams elsewhere face too. With increased components, there is an increased need to get more creative with the class names considering you do not want to run into name conflicts that will waste a lot of engineering resources in long debugging hours.
After exploring the option of longer and more creative names and coming out futile we had to get a solution. CSS modules. How? Simple, for my header component, I renamed my CSS file to “Header.module.css”
Then the importation in my header component changes from “import ‘Header.css’;” to the format below.
Then I refactored the class names in my component as shown below:
As reflected above, for every class name you prepend, “styles” and a dot(.) to it. And when you inspect the div in the browser this is how it may appear:
Basically, we are all done and won't have to worry about one class name overriding the style rules of another but we also have the disadvantage of not having any global styling rules and everything is locally scoped — which means class names are made unique at build time — also called transpiling.
For elements that you gave two or more class names, you could use composition to get the desired results. As seen below:
A class can as well be composed of more than one class as shown below.
You can as well explicitly set the different class name to the element as shown below:
That is how I am using CSS modules, maybe next I may share my experience with either Tailwind CSS or container queries; fingers crossed.