CSS Modules: What Are They?

CSS modules in its simplest definition, is a different approach to applying CSS to elements in your application. Generally, one would go about assigning a class or an id to an element and then going to your CSS file and then assigning certain attributes to it. CSS modules allow you to write everything in a JavaScript file. Look down below for an example of plain HTML vs. applying CSS modules.

Plain HTML

<h1 class=” example”>Plain HTML</h1>

index.js

.example {
color: red
}
styles.css

styles.css

CSS Modules

import styles from ‘./styles.css’element.innerHTML = `<h1 class=”${styles.example}”>
Plain HTML
</h1>`

index.js

.example {
color: red
}

styles.css

Notice the difference between the two? You might also notice when you inspect the class of the element, you get some sort of unique name. This is because when you use CSS modules, a class name gets randomly generated.

So now you might wonder what would be the purpose of CSS modules. There are a few reasons to!

One advantage of CSS modules is that, everything’s in one place. You don’t have the inconvenience of having to switch between files or bother sifting through your stylesheet. Another advantage is that each element you create using CSS modules has a unique class name so whatever attributes you decide to assign it only applies to that element and that element alone. Another huge advantage is scalability.

In summation, CSS modules are great and have many advantages. One thing I will mention is that its necessity is dependent on how big the application or website is. Even for medium to large projects, CSS modules become a necessity. I would say that if you’re building a small side project, it is absolutely not necessary to use CSS modules. Please check out the links I provided down below for more information.

Flatiron School Alumni & Software Engineer https://jonathanwong110.github.io/JonathanWongPortfolio/