DEV Community

Discussion on: Code-efficient Theming and Coloring in CSS thanks to an OOP-inspired pattern

Collapse
 
invaderb profile image
Braydon Harris

I really like this approach very well thought out and great article! I'll have to play around with this.

while I'm not a huge fan of css-in-js myself I like the dynamic aspect of it, I'm curious your thoughts on why to avoid it?

Collapse
 
drno profile image
Dr No • Edited

Thanks you for your comment and for reading ! I will write, hopefully tomorrow, a second part on how to use multi variable setters to achieve more complex looks.

Here are in my view the so-called advantages of CSS in JS :

  • Allows for a "dynamic" aspect, as you say with different kinds of variables
  • Makes a 'build system' default, to can take care of anything from minimizing the code, renaming the classes to something random, to subsequently namespace components

If we debunk a bit this, and reflect on the pattern, we realize

  • It silos the CSS/SCSS into javascript modules, which goes against the DOM principle of language/function separation. Also, there's a need to configure a specific linter/syntax hightlighting having some 'unnatural' nested syntax in JS.
  • It's actually quite easy to implement a SCSS/CSS build system independently of javascript (sass src/main.scss dist/main.css -I ./node_modules -c --no-source-map && postcss dist/main.css -o dist/main.mincss is simply as powerful, and does miracles with a nodemon script)
  • Namespacing of modules goes against the very concept of CSS being cascading, in other words CSS is being by nature a scoped language, and the process of properly learning CSS should imply learning how the scoping works (including, for more advanced developpers, understanding how CSS scoping and CSS variables relate to the Shadow DOM)
  • Also, the variables use following CSS-in-JS can be mostly implemented using vanilla CSS (not even using a preprocessor), for instance .component { padding : calc(var(--page-padding) / 2)}. A bit more verbose, that's true (some would say ugly), but I believe that puts to good use the CSS specs. For the colors, that's a bit less obvious, but that's also why I wrote this article !
  • More importantly, it invites beginner / intermediate developpers to "not think" about these problems and jump straight ahead to the solution, even though this solution is highly opinionated and creates what is in my view an unnecessary dependency on javascript to seldom manage stylesheets.
  • Finally, it removes the satisfaction of finding solutions in just CSS ! 😊

This is only my modest view on it. Maybe I'm missing out on some particulars of it, or maybe I'm very old fashioned by having this view, what do you think ?