hjertnes.blog

CSS In JS

28.07.2019 10:29

CSS in JS is a kind of new thing everything considered. Instead of writing your CSS in a CSS file you write it in some kind of JavaScript object. It can be like as simple as the default React style objects that is just a javascript object where you define css properties like color, border etc. Or something like styled-components where you write regular css, but it is scoped and you can pass properties / parameters to it. There are more too, but these are the ones I am familiar with. The big difference between them is that using a plain js object to represent css styling excludes a large portion of the CSS syntax. Like media queries for example. While everything that is possible in CSS can also be done with something like styled components.

A lot of people hate css in js. And there are good reasons for it. Writing regular CSS is the ideal, because then you can just take your styling and bring it along when you change from React to the next big thing. And you can also combine different technology and use the same styling. But when someone are using CSS in javascript and have thought through way they are doing it there is a really good reason for it. A problem with CSS when you are building large web sites or web applications is that the stylesheets you are loading are global. And my experience is that it is really hard to build systems that are easy to use, extend, maintain etc with regular CSS. This is the thing CSS in JS solves. It is always easier to build good software when you only have to think about a small part of it. This is why we do micro frontend, microservices and css in js.