Have you ever been styling a component, only to realize that unwanted CSS rules are being applied?
Maybe you then go refactor another section of the CSS so the rules don't apply,
or maybe you throw up your hands and add some
!important rules just to get it
This is the problem that CSS Modules solve. Let's look at the official definition of a CSS Module:
A CSS Module is a CSS file in which all class names and animation names are scoped locally by default.
By the way, a 'CSS Module' is just a
.css file. You call it a 'CSS Module' if
you plan on using it with a CSS Modules compiler.
Let's visualize what we have so far:
A CSS Module goes into the compiler, and CSS comes out the other side.
Where do you get a CSS Modules compiler? If you are using Webpack, you already have one. Just add the "?modules" option to "css-loader". For an example, see: github.com/css-modules/webpack-demo
If that's too abstract for you, let's take a concrete example:
Notice how the
meow class is renamed to
cat_meow_j3xk. Let's break that
cat: the file name
meow: the local class name
j3xk: a random hash
These combine to create
cat_meow_j3xk which is unique globally. This is
important because your browser doesn't have a concept of 'local scope' for CSS.
If CSS rules are not unique globally, then they will overlap.
So far so good, but how do you get that globally unique name? Are you going to
className="cat_meow_j3xk" in all your React components? Of course not.
Here's the updated concrete example:
meow as a key, and that matches the
class name that you chose in your CSS Module.
object.meow will give you the
On big projects, this approach really pays off.
The real joy of working with CSS Modules is this:
Whenever I start a new component, I know that there are no global styles that will interfere with my work.
Still confused? Maybe you learn better with examples? Check out CSS Modules by example. I run you through a list of the most common scenarios you'll encounter with CSS Modules, and I show you exactly how the CSS Modules compiler will behave in each instance.
By the way, it took days for me to figure out what CSS Modules are and how they work. Let me help you learn everything more quickly. Sign up for my newsletter below for more guides like this one.