Skip to content
css-in-js

How to get started with CSS-in-JS

June 4, 20202 min readCSS-in-JS, CSS Architecture
Source: Vecteezy

What is CSS-in-Js? What challenges it poses to developers? But before we get started let’s not forget that CSS is awesome, and it’s easy to get started with. So why we need to write CSS in Javascript and how to do it.

CSS-in-JS bridges the gap between CSS and JavaScript, it doesn’t meant to destroy everything you love about CSS. My opinion is, it can make authoring CSS far more enjoyable, and I’d encourage you to give it a shot.

Why CSS-in-JS

Web applications have been scaling at a massive and complex rate, and they are Javascript heavy, just look at React ecosystem. You can still write regular CSS, you can use CSS Preprocessor like SASS, you can use CSS Modules etc. All these methodolgies are sufficient in styling your React applications. These methodolgies works perfect when you have to work on static site like marketing website, microsite or small projects.

CSS-in-JS goes one step ahead and solve numerous problems which above methodolgies can pose in developing dynamic web applications. It eliminates problems such as:

  • Global namespace
  • Style dependencies
  • Dead code elimination
  • Composition of styles
  • Sharing constants

How it works

CSS-in-JS is an approach where styles are written in JavaScript instead of in external CSS files to easily scope styles in components, eliminate dead code, encourage faster performance and dynamic styling, and more.

Here are key features:

  • CSS-in-JS allows you to write CSS in JavaScript syntax
  • It takes advantage of native JS syntax features
  • Colocate styles with components

To get started I would recommend Styled Components

Learn CSS before CSS-in-JS

Well CSS-in-JS is awesome in it’s own way, you still need to learn CSS fundamentals as it does not teach you how CSS works in DOM.

Here are key points to learn:

  • How CSS properties work
  • How inheritance works
  • How CSS layout works

Other Advantages of CSS-in-JS

Key points:

  • Easy to pre-render important CSS
  • Supports dynamic styling (Use ES modules and scope)
  • Styles are generally “scoped” to a specific component
  • Unit testing is far easier with CSS-in-JS
  • Performance improvements like critical CSS with no additional setup needed

Having said that if you are familiar with JavaScript CSS-in-JS helps remove the need to use native CSS syntax and this can make styling an application more accessible because there are fewer new things to learn. On other side of coin if you are less familiar with JavaScript your learning curve will increase but it’s not very difficult and it will only enhance your knowledge.

Happy Learning!

Powered by