CSS Modules

What are they good for?

Specificity goodness

  • Protect module scope
  • Avoid clashes and overwrites
  • Couple your CSS with your JS

How do they work?

Via a module loader

Webpack and Browserify both offer CSS module plugins that will generate the necessary code

As a post process

The task runs after you have written your CSS/SCSS/LESS

Before

.base {
  color: deeppink;
  max-width: 42em;
  margin: 0 auto;
}

After

._20WEds96_Ee1ra54-24ePy {
  color: deeppink;
  max-width: 42em;
  margin: 0 auto;
}

Before

import styles from './styles.css';

element.innerHTML = `<div class="${styles.base}">
  CSS Modules are fun.
</div>`;

After

<div class="_20WEds96_Ee1ra54-24ePy">CSS Modules are fun.</div>

They are parsed into unique strings

This requires a loading step

It's almost impossible to have clashes

:]

It's about encapsulation

You can share styles 

  • The plugin can group selectors
  • It can live alongside global CSS
  • Composition can be done in the JS

Extending (sharing)

.base {
  composes: appearance from '../AnoherModule/styles.css';
}

Global Styles

:global(.clearfix::after) {
  content: '';
  clear: both;
  display: table;
}

So how does it get into the HTML?

const html = ` 
    <div class="${styles.root}"> 
    <img class="${styles.image}" src="${data.image}" /> 
    <p class="${styles.description}">${data.description}</p> 
    </div> `;

Resources

http://chrispearce.co/elephants-the-three-code-ilities-two-months-with-css-modules/

 

http://www.sitepoint.com/understanding-css-modules-methodology/

 

https://github.com/css-modules/webpack-demo

Made with Slides.com