top

A journey into CSS and then into CSS-in-JS

This blog post details on how my journey was towards learning the principles of plain CSS, then pre-processors and then finally stumbling upon the CSS-in-JS ecosystem and what benefits it actually gave me in my path. CSS is easy. It’s like riding a bike, which is on fire and the ground is on fire and everything is on fire because it is hell. — I Am Devloper (@iamdevloper) July 14, 2016   Enter into styling Having worked with backend core technologies primarily, in the beginning, it was difficult to understand the principles or thought process in designing html. Most of the times I used to just get along copy pasting HTML/CSS from other websites or dig into stackoverflow. But down the line, it got serious, I had to involve myself in truly understanding the core concepts with styling, Grabbed a book from internet and went ahead right away into styling with vanilla css, but since those were the initial stages, I had to work a lot into handling interactions, switching styles dynamically based on some app state, reuse of style blocks. Although things worked, it took a fair share of workarounds and follow-ups on what other people were doing to accomplish the same.   Source: https://speakerdeck.com/vjeux/react-css-in-js Some points to note: Css solves the problem of styling documents in general and its capabilities are ever growing Hard to introduce logic into plain css. Difficult to reuse blocks of styling or achieve inheritance. Maintenance is a very big problem and keeps getting bigger as we scale. Hard to target browsers without tooling like vendor prefixing.   Enter into pre-processors Use of build time tools really helped some of the pain points that vanilla css had. Smaller blocks could target a specific component and helped in being shared over to other parts. Having a well-defined structure of css file would easily help onboard a lot of people into styling. This resulted in improved Developer Experience (DX) and in turn improved productivity. We could use features such as nesting, variables, loops, and math. Trust me, it felt like unlimited power until it started showing up some drawbacks again. Some points to note: Pre-processors like less/sass/postcss help transform some logical constructs into plain css. Helps achieve writing reusable, maintainable and extensible styling css. Involves tooling and requires a fair amount of learning as compared to regular css (more like extended learning). Maintaining styles can become an overhead as the application scales. Requires us to follow specific methodology (e.g. BEM) in order to avoid styling conflicts. When the application is huge, this still might not help and can lead to conflicts with other elements being styled. Can still result in a lot of unused styles than required in the present state the application would be in. For e.g. without proper structuring, you could pull in, let’s say profile page css into the main landing page css. Browsers won’t complain.   Behold CSS-In-JS After working for quite a good period in web development going along pre-processors, we had to move parts of the application into a new javascript powered stack from our old PHP based. We saw that during this thinking process of laying down the migration path, Css-In-Js was running around and a number of companies have been using it in their production grade apps, We definitely wanted to see if the problems we faced with pre-processors would be taken care of. The extensibility of these tools could even let you gracefully shift to the new stack while maintaining the entire stack in place. Initially, onboarding a lot of people who were just into css and not much into js did take time. But gradually, they did see the benefits and now it has helped in the output we create at the end with amazing DX. DX is equally important since, how and what we craft is what’s going to result in the end users’ view. JavaScript is a powerful language and making styling in js meant that you can use and leverage full power of the language into CSS. However there are still some thoughts in the wild around communities that writing all in JS is a bad idea. But hey! What works for you is what’s the best out there. What really helped us manage well was the way we perceived separation of concerns. This talk “Let there be peace on CSS” by Cristiano Rastelli shows a very good viewpoint into modules methodology. In other words: CSS — You apply your styles and you hope it worked. JavaScript — You control the styling and you can and should verify that it worked CSS — It is the job of the browser to perform well, use GPU resources and skip functionality. JavaScript — It’s your job to test for support. And to ensure rendering, painting and reflow are fast. And to keep animation in sync Ref: @codepo8 Some points to note: It is still CSS, but leverages Javascript capabilities. Tooling with css-in-js is evolving day by day. Although widely adopted, doesn’t mean it will solve everything, there is still some experimentation at cracking the right amount of perfection and at the same time improving developer experience by a ton. Helps avoid naming collision or conflicts since most of the libraries have BEM conventions “baken-in”, not an opt-in. Computers are good at naming uniquely any day. Most of the constructs that pre-processors bought can be easily done since it is already in Javascript capabilities. Since it is all JS, building tools like webpack and some dynamic libraries help in Dead Code Elimination and Minification to target only required styles per app. Optimal code sharing since javascript is inclining towards a very good module system. Isolation! A component piece created can be used at multiple places without affecting other styling.   One approach that worked out really well.. React, Fela and Styleguidist driven development: React is A JavaScript library for building user interfaces. To know more about Reactjs Fela is a small, high-performant and framework-agnostic toolbelt to handle state-driven styling in JavaScript. To know more about Felajs React Styleguidist is a Isolated React component development environment with a living style guide. To know more about React Styleguidist We choose the above combination of tools since they help with component-based approach into developing UI layers. React for its component model capabilities, Fela for css styling being tiny, fast and modular, React Styleguidist for the environment to create and play around the components and lock in the UI primitives. This helped in maintaining the UI components well and keeping them as a separate package that the core application uses. Basic components with React & Fela A simple style when using fela from official doc would be like below // a simple style rule is a pure function of state // that returns an object of style declarations const rule = state => ({   textAlign: 'center',   padding: '5px 10px',   // directly use the state to compute style values   background: state.primary ? 'green' : 'blue',   fontSize: '18pt',   borderRadius: 5,   // deeply nest media queries and pseudo classes   ':hover': {     background: state.primary ? 'chartreuse' : 'dodgerblue',     boxShadow: '0 0 2px rgb(70, 70, 70)'   } }) Below is a demo playground that shows capabilities of using fela with react. I have written appropriate comments describing what each step does. More examples using fela are here. Fela doesn’t need React to work and works with major view libraries and also has works with React Native. In the end, Fela uses a single renderer instance that keeps track of all the generated styles and with efficient caching it keeps the generated output to a minimum. Win Win! Injects the styles (Actual css in style tag not inline css) in runtime like below (uses a plugin for readable class names) and is dynamic by default. Without plugins and in production mode, fela uses atomic class names, which helps reduce the duplication of style and uses efficient reuse of repeating styling. Embracing a Component Guide/Catalog Environment React Styleguidist based on fela can be found here, try it out. It uses webpack under the hood, more on basics of webpack can be found here. Below I am just going to highlight the important parts. Break the view into basic primitive components like buttons, icons, lists, wrappers, loaders etc Compose bigger components using the smaller components. Leveraging fela’s dynamic capabilities make the components react upon styles or view depending on props passed. So multiple variants of the same component are achievable and controlled via props. Once the component implementation is finalized in the style guide, we could just import it into the application and wherever it is used they stay independent (Isolation). Any feature update in the component or change of guideline will result in the entire application without change at numerous places. Style guide becomes the source of inception of all components. Can be built as a separate package and kept as a dependency to the application. Multiple applications can make use of the same guidelines.   Some Final Thoughts Css-In-Js is growing at a rapid pace. If you are happy with existing css paradigm, you might not need Css-In-Js tooling. But someday the need might arise given its benefits. Community is working towards solving some existing concerns like static extraction, no Js runtime etc. Some have even gone far to achieve close to it. There are ton of libraries, pick one that suits and go hacking. Some benchmarks on various libs can be found here. CSS-In-Js is still Css leveraging Js. If too much JS is bothering you, take a look at CSS Modules, with a bit of tooling you can solve most problems with plain/pre-processor CSS. Trends are growing, below are few.
Rated 4.0/5 based on 0 customer reviews
Normal Mode Dark Mode

A journey into CSS and then into CSS-in-JS

Prithvi Raju
Blog
06th Mar, 2018
A journey into CSS and then into CSS-in-JS

This blog post details on how my journey was towards learning the principles of plain CSS, then pre-processors and then finally stumbling upon the CSS-in-JS ecosystem and what benefits it actually gave me in my path.

 

Enter into styling

Having worked with backend core technologies primarily, in the beginning, it was difficult to understand the principles or thought process in designing html. Most of the times I used to just get along copy pasting HTML/CSS from other websites or dig into stackoverflow. But down the line, it got serious, I had to involve myself in truly understanding the core concepts with styling, Grabbed a book from internet and went ahead right away into styling with vanilla css, but since those were the initial stages, I had to work a lot into handling interactions, switching styles dynamically based on some app state, reuse of style blocks. Although things worked, it took a fair share of workarounds and follow-ups on what other people were doing to accomplish the same.

Enter into styling 

Source: https://speakerdeck.com/vjeux/react-css-in-js

Some points to note:

  • Css solves the problem of styling documents in general and its capabilities are ever growing

  • Hard to introduce logic into plain css.

  • Difficult to reuse blocks of styling or achieve inheritance.

  • Maintenance is a very big problem and keeps getting bigger as we scale.

  • Hard to target browsers without tooling like vendor prefixing.

 

Enter into pre-processors

Use of build time tools really helped some of the pain points that vanilla css had. Smaller blocks could target a specific component and helped in being shared over to other parts. Having a well-defined structure of css file would easily help onboard a lot of people into styling. This resulted in improved Developer Experience (DX) and in turn improved productivity. We could use features such as nesting, variables, loops, and math. Trust me, it felt like unlimited power until it started showing up some drawbacks again.

Some points to note:

  • Pre-processors like less/sass/postcss help transform some logical constructs into plain css.

  • Helps achieve writing reusable, maintainable and extensible styling css.

  • Involves tooling and requires a fair amount of learning as compared to regular css (more like extended learning).

  • Maintaining styles can become an overhead as the application scales.

  • Requires us to follow specific methodology (e.g. BEM) in order to avoid styling conflicts. When the application is huge, this still might not help and can lead to conflicts with other elements being styled.

  • Can still result in a lot of unused styles than required in the present state the application would be in. For e.g. without proper structuring, you could pull in, let’s say profile page css into the main landing page css. Browsers won’t complain.

 

Behold CSS-In-JS

After working for quite a good period in web development going along pre-processors, we had to move parts of the application into a new javascript powered stack from our old PHP based. We saw that during this thinking process of laying down the migration path, Css-In-Js was running around and a number of companies have been using it in their production grade apps, We definitely wanted to see if the problems we faced with pre-processors would be taken care of. The extensibility of these tools could even let you gracefully shift to the new stack while maintaining the entire stack in place.

Initially, onboarding a lot of people who were just into css and not much into js did take time. But gradually, they did see the benefits and now it has helped in the output we create at the end with amazing DX.

DX is equally important since, how and what we craft is what’s going to result in the end users’ view.

JavaScript is a powerful language and making styling in js meant that you can use and leverage full power of the language into CSS.

However there are still some thoughts in the wild around communities that writing all in JS is a bad idea. But hey! What works for you is what’s the best out there.

What really helped us manage well was the way we perceived separation of concerns. This talk “Let there be peace on CSS” by Cristiano Rastelli shows a very good viewpoint into modules methodology.

In other words:

CSS — You apply your styles and you hope it worked.

JavaScript — You control the styling and you can and should verify that it worked

CSS — It is the job of the browser to perform well, use GPU resources and skip functionality.

JavaScript — It’s your job to test for support. And to ensure rendering, painting and reflow are fast. And to keep animation in sync

Ref: @codepo8

Some points to note:

  • It is still CSS, but leverages Javascript capabilities.

  • Tooling with css-in-js is evolving day by day. Although widely adopted, doesn’t mean it will solve everything, there is still some experimentation at cracking the right amount of perfection and at the same time improving developer experience by a ton.

  • Helps avoid naming collision or conflicts since most of the libraries have BEM conventions “baken-in”, not an opt-in. Computers are good at naming uniquely any day.

  • Most of the constructs that pre-processors bought can be easily done since it is already in Javascript capabilities.

  • Since it is all JS, building tools like webpack and some dynamic libraries help in Dead Code Elimination and Minification to target only required styles per app.

  • Optimal code sharing since javascript is inclining towards a very good module system.

  • Isolation! A component piece created can be used at multiple places without affecting other styling.

 

One approach that worked out really well..

React, Fela and Styleguidist driven development:

We choose the above combination of tools since they help with component-based approach into developing UI layers. React for its component model capabilities, Fela for css styling being tiny, fast and modular, React Styleguidist for the environment to create and play around the components and lock in the UI primitives. This helped in maintaining the UI components well and keeping them as a separate package that the core application uses.

Basic components with React & Fela

A simple style when using fela from official doc would be like below

// a simple style rule is a pure function of state
// that returns an object of style declarations
const rule = state => ({
  textAlign: 'center',
  padding: '5px 10px',
  // directly use the state to compute style values
  background: state.primary ? 'green' : 'blue',
  fontSize: '18pt',
  borderRadius: 5,
  // deeply nest media queries and pseudo classes
  ':hover': {
    background: state.primary ? 'chartreuse' : 'dodgerblue',
    boxShadow: '0 0 2px rgb(70, 70, 70)'
  }
})

Below is a demo playground that shows capabilities of using fela with react. I have written appropriate comments describing what each step does. More examples using fela are here.

Fela doesn’t need React to work and works with major view libraries and also has works with React Native.

In the end, Fela uses a single renderer instance that keeps track of all the generated styles and with efficient caching it keeps the generated output to a minimum. Win Win!

Injects the styles (Actual css in style tag not inline css) in runtime like below (uses a plugin for readable class names) and is dynamic by default.

Without plugins and in production mode, fela uses atomic class names, which helps reduce the duplication of style and uses efficient reuse of repeating styling.

Embracing a Component Guide/Catalog Environment

React Styleguidist based on fela can be found here, try it out. It uses webpack under the hood, more on basics of webpack can be found here. Below I am just going to highlight the important parts.

  • Break the view into basic primitive components like buttons, icons, lists, wrappers, loaders etc

  • Compose bigger components using the smaller components.

  • Leveraging fela’s dynamic capabilities make the components react upon styles or view depending on props passed. So multiple variants of the same component are achievable and controlled via props.

  • Once the component implementation is finalized in the style guide, we could just import it into the application and wherever it is used they stay independent (Isolation).

  • Any feature update in the component or change of guideline will result in the entire application without change at numerous places. Style guide becomes the source of inception of all components.

  • Can be built as a separate package and kept as a dependency to the application. Multiple applications can make use of the same guidelines.

 

Some Final Thoughts

  • Css-In-Js is growing at a rapid pace.

  • If you are happy with existing css paradigm, you might not need Css-In-Js tooling. But someday the need might arise given its benefits. Community is working towards solving some existing concerns like static extraction, no Js runtime etc. Some have even gone far to achieve close to it.

  • There are ton of libraries, pick one that suits and go hacking. Some benchmarks on various libs can be found here.

  • CSS-In-Js is still Css leveraging Js.

  • If too much JS is bothering you, take a look at CSS Modules, with a bit of tooling you can solve most problems with plain/pre-processor CSS.

  • Trends are growing, below are few.

Some Final Thoughts

Prithvi

Prithvi Raju

author

Senior Full Stack Engineer at Bookmyshow. Avid Coder and Loves Javascript Fatigue.

Leave a Reply

Your email address will not be published. Required fields are marked *

REQUEST A FREE DEMO CLASS

SUBSCRIBE OUR BLOG

Follow Us On

Share on

Useful Links

20% Discount