Published 2017-1-18
CSS Modules approach - PostCSS

Introduction to Css Modules

This blog will be only quick overview of quite recent approach how to style application.

As I already used thi at few projects (SPA in React), I can just say that it's really easy to write, hard to mess up, and simple to maintain.

What I am talking about are CSS Modules.

When to use them?

I would like to saw always! But definite answer would be - use them in application which is separated into parts, or components. Best use case is probably in Single Page Applications (SPA) where you usually have components and each of them may have local styles.

To be able to use modules we need to do some preprocessing, like webpack does, or also there are more alternatives.

What are advantages ?

Image that we have more Buttons components - eg. SubmitButton and ResetButton. Each button is component with it's own style where we can type css in both components like .button { ... } with it's own styles for both buttons.

import css from './submitButton.css';
export default class SubmitButton extends React.Component {
    render () {
        return <div className={css.button}>Click Me</div>
    }
}

Then when building application, it automatically translate these css classes into unique identifiers. See html from example above:

<div class="components__submitButton__1as1das54d" />

That leads to no clashes between naming, no need to create names like .componentSubmitButton, in code we may just type .button and preprocessor will make sure classifier is unique.

This is best feature of Css Modules, to see more check PostCss, or CssModules plugin on github.

Library for modules is here - https://github.com/gajus/react-css-modules but nowadays it's even better to use Post CSS https://github.com/postcss/postcss as it contains CSS Modules and also more cool features similar to SASS, or Less.

References:

;