Why CSS in JS?

Ethan Marcotte wrote an excellent blog post called Weft:

The frameworks we build, the visual languages we formalize—they’re artifacts that ultimately live in a broader organizational context.

Two days previously, Joel Hooks sent a mailout about a CSS-in-JS Egghead course:

CSS-in-JS means that our style sheets are written and stored in JavaScript files.

I sent Joel an email, saying why not Block Element Modifier CSS and Inverted Triangle CSS? And he said something along the lines of, BEM made him and his team sad 😞.

I did not understand. Thanks to the stellar work of Nicole Sullivan, Jonathon Snook, Nicolas Gallagher, Brad Frost and many more, we have choices of syntax and ways of conceptually and visually organising the CSS (BEM and Inverted Triangle CSS by Harry Roberts being my favourites).

Inverted Code Triangle rainbow-coloured illustration

It’s easy:

  • Base styles: variables, unclassed HTML elements
  • Objects: prefixed with o-, cosmetic-free abstractions
  • Components: discrete blocks of UI
  • Utilties: high specificity, very explicit helper classes

The components are organised by uniquely named directory, each containing the CSS, JS, SVG etc required for that component. Hell, you can even include HTML template snippets for the excellent Fractal component library. So why the need for CSS-in-JS?

Ethan’s words came back to me…

…artifacts that ultimately live in a broader organizational context

Me: CSS developer / You: JS developer

Brad Traversy has an excellent Modern JavaScript From The Beginning course, and I was struck by his use of Bootstrap. It’s a JavaScript course, he doesn’t have time to get into the CSS, so in that context, Bootstrap is good enough.

The light bulb moment 💡, I realised that CSS-in-JS and CSS utility frameworks are for JavaScript developers, specifically React developers.

  • Base styles: write lightweight ones yourself
  • Components: eg Emotion, which is CSS-in-JS specific to React components
  • Utilities: eg Tailwind utility first CSS framework

This is component CSS in the context of JavaScript developers, with less cognitive overhead. Let’s face it, with the full-stack being loaded on the frontend, JavaScript developers have enough to get their heads around without becoming CSS masters as well.