Looking to try CSS in Javascript? Have a read to see which approach to take


As the name would suggest, this is all about defining cascading stylesheets in JavaScript. It provides an abstraction of CSS using JavaScript as a language to describe styles in a declarative and maintainable way. The CSS in JS is compiled either at runtime or server- side providing high performance with very low overhead.

When CSS debuted in 1996, the premise was that content should be divorced from style, allowing the author to concentrate on the former, and the end-user (reader) able to tweak the latter to taste. Comic Sans became popular not too soon afterwards, surely related, perhaps the first real indication that this was in fact a major mistake.

Fast forward almost two decades to 2014, when Christoper ‘vjeux’ Chedeau’s gave a well received 2014 talk on CSS in Javascript, attempting to fix many of the problems that resulted from this early decision. A proliferation of libraries followed, aimed at improving the styling of component based applications and once again tying together content and style more closely together.

By offering a locally scoped alternative to globally scoped traditional CSS (something that CSS Modules also give us), we can do away with many of the naming conventions (BEM, SMACSS etc) used to combat the problems caused by global scoping, such as the accidental overriding of styles. This results in a significantly simplified developer experience, being able to ensure that individual changes do not have unexpected flow-on effects.

CSS in Javascript libraries largely fall into two categories - those that make use of tagged template literals, such as Styled Components, and those that use built-in Javascript data structures such as Glamorous and Styletron.

There is a fair amount of debate within the Badger camp as to which, or indeed any of these options are advantageous. Reflecting this, the current state of CSS in Javascript is extremely fragmented, with a total of 59 libraries currently listed on Michele Bertoli’s useful comparison of options available to React users, a clear winner yet to emerge.

This perhaps explains why Emotion, despite being relatively recent addition, has rapidly picked up stars on github, offering the option of both object and css string approaches, and wrapper around it’s core functionality with a Styled Component-like feel should you wish to use it use it over the primary ‘css’ function.

Given this flexibility, if you are looking to give CSS in JS a go, Emotion would probably be a good place to start in 2018, allowing you to decide for yourself which approach to take. 

 Read the Tech Round Table now.

Sign up to Badger News