Discussion on: Classical CSS vs CSS in JavaScript

moopet profile image
Ben Sinclair

My bias is that I don't use Javascript much, and I don't use componenty things like React at all.

But I strongly dislike CSS-in-JS, and disagree with anyone who says that it's a good separation of concerns.

I think that the CSS-in-JS movement came built on two trends.

First, the "framework" idea where CSS is used as shims for inline styles, with utility classes such as "large-text" or "padding-right-10" or whatever, and millions of non-semantic wrappers. These break any separation of content and presentation you might want by meaning you have to update your HTML every time you change anything about your appearance.

Second, the rise of node. People jumped aboard node more than previous languages/frameworks because they often already knew a lot of the language from classical Javascript, and because they saw an opportunity to re-make something in a relatively easy manner. Suddenly a million people without an original idea between them could put that they were the "maintainer" (or "creator" if they were being particularly shifty) of a package onto their next job application.

These together mean that the world is unapologetic about crossing style and semantic concerns or about needlessly remaking everything in JS.

When CSS-in-JS came around they didn't stop in their tracks and say, "hold up". It doesn't seem like a bad idea to them.

If I have a widget and I want to place it on a site in a main content area or a sidebar or a footer, I want it to get its styles from the cascade. CSS-in-JS simply can't do this, unless you import a bunch of common styles inside each widget. I've seen that advocated, and you know what? It's reinventing the cascade. Why import common styles in JS when you already have a way of doing it? One that won't break when your script throws an exception or fails to load?

I think, if anything, it should be called Style-in-JS, because it's not CSS. It doesn't use its own stylesheet and it avoids the cascade. Style-in-JS is OK. It's not exactly nice, but who hasn't written a hack somewhere that does more than a display: none toggle when there's no obvious easier way?

It's just, well, if I edit styles in my JS, I'd add a comment saying // @TODO: move these to a stylesheet.
And if I was going to keep CSS tied to JS, I'd at least keep it in a separate file.

bizzibody profile image
Ian bradbury

Well said.