Crane Cloud
Published in

Crane Cloud

Using CSS Modules

Photo by Nick Karvounis on Unsplash

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.

How I import CSS into my component.

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:

How the div looks like when inspected in a browser.

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:

In the second class is “composed” of the first by use of the “composes” keyword as shown.

A class can as well be composed of more than one class as shown below.

The BrandLink classes is “composed” of both the BannerLink and HeaderLinks classes.

You can as well explicitly set the different class name to the element as shown below:

Added two classes to this particular element.

That is how I am using CSS modules, maybe next I may share my experience with either Tailwind CSS or container queries; fingers crossed.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store