×
Community Blog A Detailed Explanation of CSS-in-JS

A Detailed Explanation of CSS-in-JS

This article gives a thorough explanation of CSS-in-JS, including where it is today and where it is going in the future.

By Zouyue

A few years ago, if someone mentioned writing HTML in JavaScript as a way to build large websites, many developers would take this as an unreasonable idea. Now, applications developed for components using React, Vue, and Angular frameworks are gradually replacing traditional Web development.

Now, CSS-in-JS is like the past. It is not the only solution, but it provides a bold idea and attempt.

The same is true for modern Web development projects. CSS is no longer the only choice to present rich Web applications as a style sheet for the Web. Perhaps we should consider other extensibility and portability to try future CSS-in-JS.

1. An Introduction to CSS

Cascading Style Sheets (CSS) is a computer language used to add styles to structured documents, defined and maintained by the W3C. The latest version is CSS2.1, which is the recommended standard of W3C. CSS3 is now supported by most modern browsers, while the next version of CSS4 is still under development.

1.1 Modules and Standardization Processes

It took nine years (from August 2002 to June 2011) for CSS Level 2 to reach the recommendation status, mainly because it was held back by some secondary features. In order to speed up the standardization of features that have been confirmed to be no problem, W3C's CSS Working Group (CSS Working Group) made a decision called the Beijing doctrine, dividing CSS into many widgets called _modules_. These modules are independent of each other and standardized according to their respective schedules. Some of them are already in W3C Recommendation status, while others are still early Working Drafts. When new requirements are confirmed, new modules will be added the same way.

The first CSS was launched in 1996. Here is the schedule of CSS versions:

  • CSS 1.0 released in 1996.
  • CSS 2.0 released in 1998.
  • CSS 2.1 released in 2011.
  • The CSS3 module extended the CSS 2.1 in 2021

1

1.2 CSS Module Status

Formally, the CSS3 standard itself no longer exists. Each module is independently standardized. Now, the standard CSS includes the revised CSS2.1 and the expansion of the complete module. The number of levels (levels) of the modules is not consistent. You can define snapshots (snapshots) for CSS standards at each point in time to list CSS 2.1 and mature modules.

W3C will regularly release these snapshots, including 2007, 2010, 2015, and 2017.

So far, no module with a level over 3 has been standardized, but it should change in the future. Some modules, such as Selectors 4 or CSS Borders and Backgrounds Level 4, already have Editor's Draft, even if they have not reached the First Published Working Draft status.

2

1.3 Five CSS Design Patterns

Modern frontend development has developed many CSS design patterns in history, mainly the following:

  • OOCSS (Object Oriented CSS)
  • SMACSS (Scalable and Modular Architecture for CSS)
  • BEM (Block - Element - Modifier)
  • ITCSS (Inverted Triangle Cascading Style Sheets)
  • Atomic CSS

The reason for its design is mainly based on these problems to realize optimization:

  • Reduce conflicts between selector naming and styles
  • Clear CSS overall structure
  • Remove redundant codes and reduce the volume of styles
  • Reusable, componentized CSS
  • Improve the readability of CSS code

1.4 History of Atomic CSS

3

  • 2013/06/10: Brad Frost published an Atomic Design article. There are articles in the community that start discussing Atomic CSS.
  • 2015/01/08: Atomic Design, an essential web development book, was released.
  • 2014/10/02: The atomizer project was created.
  • 2017/10/06: The tailwindcss project was created.

Tailwind CSS is relatively unpopular compared with other precompilers, as shown in the following figure:

4

In the increasingly popular Web development world of React and Vue, the idea of componentization and engineering are maturing day by day. Atomic CSS is also a design idea introduced earlier. The author thinks that what Atomic CSS can do is better in CSS-in-JS. Atomic (atomization) is a CSS-in-JS area that can be involved in the future because of the prevalence and abundance of JS frameworks and tools.

1.5 CSS Math Expressions

According to the draft of CSSWG, the mathematical expressions currently supported by CSS include five main categories:

  • Fundamental Arithmetic: calc()
  • Comparison Function: min(), max(), clamp()
  • Step Function: round(), mod(), rem()
  • Trigonometric Function: sin(), cos(), tan(), asin(), acos(), atan(), atan2()
  • Exponential Function: pow(), sqrt(), hypot(), log(), exp()

Calc () is the most commonly used daily. It is generally used to calculate length, width, and responsive layout, while comparison functions may also be used in some scenarios. Most of the remaining functions have no chance to be used in projects.

5

1.6 CSS Houdini

Houdini is a set of underlying APIs that expose parts of the CSS engine, enabling developers to extend CSS by adding the styling and layout process of the browser rendering engine. Houdini is a set of APIs that give developers direct access to the CSS Object Model (CSSOM) and enable developers to write code that the browser can parse into CSS, creating new CSS features without waiting for them to be implemented natively in the browser.

-MDN / CSS Houdini

If CSS-in-JS is a set of schemes that use JS to control, extend, and carry out the real-time linkage of CSS with the existing standard. Then, CSS Houdini is an advanced version of CSS-in-JS. Developers can extend CSS better by exposing various functions of the CSS engine. I think the emergence of CSS Houdini also means it has been difficult for the current pure CSS to meet the increasingly rich Web applications.

6
CSS Houdini

CSS Parser API

This is an API interface that directly exposes the CSS parser, which can parse any CSS class language into an intermediate type and define a new structure.

CSS Properties and Values API

  • Define an API for registering new CSS properties. Properties registered through this API must be written in a specific parsing syntax to define their type, inheritance behavior, and initial value.
  • CSS Properties and Values API Reference
  • CSS Properties and Values API Guide

CSS Typed OM

  • CSS Typed OM can be regarded as CSSOM 2.0. Its purpose is to solve some problems of the current model and implement the features of CSS Parsing API and CSS attributes with value API.
  • CSS Typed OM reference
  • CSS Typed OM guide

CSS Layout API

An API designed to improve CSS extensibility allows developers to write their own layout algorithms, such as masonry or line snapping.

CSS Painting API

  • An API designed to improve CSS extensibility allows developers to write JavaScript functions through the paint() method to control the style or content area in which page elements are drawn.
  • CSS Painting API reference
  • CSS Painting API guide

Worklets

  • This API allows scripts to run at various stages of the rendering process independently of the JavaScript execution environment.
  • Worklets are extended and called by the rendering engine in Web Workers close to JS.
  • Worklets Reference

1.7 CSS Preprocessor

CSS Preprocessor is a program that allows you to generate CSS using the preprocessor's unique syntax. There are many CSS preprocessors on the market to choose from, and most CSS preprocessors will add some features that native CSS does not have, such as code mixing, nested selectors, and inheritance selectors. These features make the CSS structure more readable and easy to maintain.

-MDN / CSS Preprocessor

Some of the most popular CSS preprocessors:

  • PostCSS: 2013/11/04
  • LESS: 2009
  • SASS: 2006/11/28
  • Stylus: 2010/12/29

7

As shown in the figure, the download volume of PostCSS has been far ahead of other CSS preprocessors. The advantage of PostCSS is that there are many plug-ins available in the community, which is equivalent to Babel of CSS. Common PostCSS plug-ins are listed below:

  • Autoprefixer: Auto-complete browser private prefixes
  • precss: CSS preprocessing (integrates Sass, LESS, or Stylus functions, and the syntax is virtually the same as Sass)
  • postcss-import: Integrate multiple CSS files through @import
  • css-mqpacker: Combine the same CSS media query rules into one
  • cssnano: Compressing CSS Files
  • postcss-color-rgba-fallback: Create a degradation scheme for RGBA colors (add alternate colors)
  • postcss-opacity: Provide a degradation scheme for opacity (add filter property to IE browser)
  • node-pixrem: Allows IE 8 to support rem units
  • postcss-pseudoelements: Convert the pseudo element :: to : ( IE8 does not support ::)

8

If you must use CSS preprocessor, PostCSS may be one of the best choices. You also need to check the overall plan of your project.

1.8 CSS-in-JS vs. CSS Preprocessor

9

In Google Trends, we can see the trend of CSS-in-JS has gradually surpassed CSS preprocessors after 2014, which also shows that developers have a great interest in CSS-in-JS.

2. An Introduction to CSS-in-JS

CSS-in-JS is a styling technique in which JavaScript is used to style components. When this JavaScript is parsed, CSS is usually generated.

2.1 CSS-in-JS Origin History

  • November 13, 2000: The Document Object Model (DOM) Level 2 Specification proposed CSS Object Model (CSSOM) in the W3C draft allows CSS to be manipulated using JavaScript. It is similar to DOM but is used for CSS instead of HTML. It allows users to read and modify CSS styles dynamically.
  • November 15, 2014: The CSS-in-JS was proposed by Facebook employee Vjeux at the NationJS conference. JS can be used to solve some defects of many CSS itself, such as global scope, dead code removal, effective order depending on style loading order, and constant sharing.
  • 2014-Present: A large number of CSS-in-JS solutions have been proposed, constantly innovating in the field and exploring the implementation of engineering and framework solutions.

One of the major characteristics of CSS-in-JS is that it has many schemes. This seemingly chaotic state is consistent with the characteristics of the frontend community that tends to make wheels repeatedly. In the early stage of development, the community explored the possibility of developing and maintaining CSS with JS in various directions. Every once in a while, there will be new syntax schemes or implementations, aiming to supplement, enhance, or fix existing implementations.

2.2 Platforms and Frameworks without CSS

  • QT: QStyle Class and Draw Method
  • Flutter: Style Object
  • ReactNative: ReactNative.StyleSheet
  • Unreal Engine: Style Object
  • Canvas: Draw Method
  • Skia: Draw Method

They are all written based on their design imperative and declarative styles, which can be bound to each state in the program design, and are not limited to the concept of style sheet modification.

2.3 What Are the Differences?

In my opinion, the difference between pure CSS framework tools and CSS-in-JS is the different timing of compilation and operation. We can understand that CSS framework tools are only equivalent to AOT (Ahead-of-time), while CSS-in-JS has JIT (Just-in-time) capabilities. For example, the CSS Houdini API mentioned above is essentially the same as extending the ability of CSS frameworks to run in real-time, while JIT frameworks and tools can essentially be optimized using AOT tools, such as Babel and Webpack.

2.4 Advantages of Using CSS-in-JS

  • The componentized thinking mode no longer requires maintaining a bunch of style sheets. CSS-in-JS abstracts the CSS model to the component level, not the document level (modularity).
  • CSS-in-JS leverage the full features of the JavaScript environment to enhance CSS.
  • Real Selector Isolation: Range selectors are not enough. CSS has attributes automatically inherited from the parent element, if not explicitly defined.
  • CSS needs to avoid selector conflicts. Naming conventions (such as BEM) may be helpful in a project, but there are many problems when integrating third-party code. When JSS compiles the JSON representation to CSS, it generates a unique class name by default.
  • Dynamic browsers privatize prefixes and use CSS-in-JS to avoid bloated CSS code.
  • Code sharing to easily share constants and functions between JS and CSS
  • Unitization test of CSS-in-JS
  • Supported by TypeScript
  • Reduce dependencies on project compilation, such asure JS or TS projects
  • Dynamically changing themes and variables

2.5 Disadvantages of CSS-in-JS

  • Learning curve/need to learn to use
  • New Dependencies

2.6 Popular CSS-in-JS Libraries

Run-Time (JIT)

Run time libraries for dynamically modifying styles:

  • emotion
  • jss
  • styled-components
  • aphrodite
  • radium
  • glamor

The following statistics show that emotion, jss, and styled-components have a good performance in terms of developer NPM download usage, maintaining a long-term growth trend, which is relatively good for developers and means these libraries are also steadily developed and maintained.

10

The increasing number of downloads year by year reflects the expansion of the development community and the scope of use. It also shows the active contribution and participation of developers in the CSS-in-JS.

11

Most of the dynamic modification styles of these libraries mainly adopt these methods:

1) CSS Style Sheet

  • Scoped CSS: Add CSS style sheets through each component with the scope.
  • Global CSS: Add and modify the content of the style sheet to modify the style globally in HTML.

2) CSSOM Modification

  • Modify the style by modifying the CSSRule of the global CSSOM

The author recommends CSSOM modification. The HTML structure and content of the page will not change, nor will there be too many single-component CSS. Moreover, there is a lot of room for optimization and expansion in modifying the style. It is hoped that subsequent developers will have excellent practices to promote.

Build-Time (AOT)

A library compiled into CSS style sheets in advance:

  • Linaria

The advantage of compiling ahead of time is that some applets and other frameworks require CSS style sheets as the only option, which is more advantageous than dynamically modifying styles on users' low-end phones and in terms of performance.

2.7 Who Is Using It?

UI Library

The material-ui is an open-source UI component library of material design the author paid close attention to for a long time. Developers that have used ReactJS may have known about it. The official adopted an inline style at the beginning, developed its own set of CSS-in-JS implementation schemes, and separately released the style scheme used in Material-UI components- @material-ui/styles.

Enterprise

Thousands of enterprises are using CSS-in-JS to develop Web applications:

  • Google
  • Facebook
  • Reddit
  • Patreon
  • Target
  • Atlassian
  • Vogue
  • GitHub
  • Coinbase

2.8 Chrome Devtools Support CSS-in-JS

Google updated support for style editing for CSS-in-JS frames in DevTools (Chrome 85).

The Styles pane now provides better support for editing styles created using the CSS Object Model (CSSOM) API. Many CSS-in-JS frameworks and libraries use the CSSOM API at the bottom to construct styles.

You can also use Constructable Style Sheets to edit styles added dynamically in JavaScript.

Constructable style sheets are a new way to create and modify styles when using the Shadow DOM.

For example, the style CSSStyleSheet added by (CSSOM API)h1 was previously uneditable. You can now edit in the Styles pane:

12

3. UI & Code 3.0 New Era

3.1 Automated intelligence

In an era when the frontend development trend is becoming more intelligent, if you use the CSS-in-JS, it will offer great convenience and controllability in input and output in the future.

If you divide the collaborative work of frontend and design into three eras:

  • v1.0: Design resources and information require an additional illustration manually cut by the designer and cannot be copied
  • v2.0: Design resources and information are automatically generated by design files and can be copied manually
  • v3.0: Design resources and information are automatically read by design source files and code without manual copying

13

In other words, the resources and information of design files can be read into the code through interfaces, SDKs, or plug-ins, reducing the cost of manual maintenance and development and establishing a bridge between design and program to facilitate the collaborative work of both parties.

14

Nowadays, many design software has launched their own set of plug-ins or SDK for developers, as shown in the following figure:

15

3.2 Cross-Platform

CSS-in-JS has great advantages in cross-platform. JS Runtime is implemented on different system platforms, and JSON serialized data can be consumed by more platforms and languages. Pure CSS alone cannot achieve such universality and extensibility.

16

4. Future

CSS was originally designed to provide global control over styles and enrich the actual page rendering with selector extensions. CSS-in-JS does not exclude CSS styles. Instead, styles in the modern development of component granularity using CSS-in-JS can be more flexible to solve more problems in the rapidly changing complex application scenarios.

The author developed his own set of React UI library - React-UWP earlier and made a CSS-in-JS scheme based on this set of UI library. Although not many components have been used in the development in the past two years, CSS-in-JS have been used as the overall style solution, which has great advantages in component expansion, theme customization, and state synchronization. It is also expected that more excellent practices can be referred to in the following communities.

If you find any mistakes in the article, please give us feedback so we can correct them. Thank you!

References

https://www.w3.org/Style/CSS20/history.html

https://levelup.gitconnected.com/a-brief-history-of-css-in-js-how-we-got-here-and-where-were-going-ea6261c19f04

https://github.com/MicheleBertoli/css-in-js

https://zhuanlan.zhihu.com/p/165089496

https://zhuanlan.zhihu.com/p/103522819

https://zhuanlan.zhihu.com/p/59692295

https://zhuanlan.zhihu.com/p/30118092

https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

https://juejin.cn/post/6844903808049348616

https://www.infoq.com/news/2020/04/facebook-cssinjs-react-conf-2019/

https://sebastienlorber.com/atomic-css-in-js

https://dev.to/carlillo/understanding-itcss-real-case-using-itcss-in-a-ghostcms-blog-1p9b

https://engineering.fb.com/2020/05/08/web/facebook-redesign/

https://zhuanlan.zhihu.com/p/98831543

https://www.qed42.com/blog/building-powerful-custom-properties-CSS-houdini

https://laptrinhx.com/the-future-of-css-has-come-3034181035/

https://zhuanlan.zhihu.com/p/20939640

https://www.smashingmagazine.com/2016/03/houdini-maybe-the-most-exciting-development-in-css-youve-never-heard-of/

https://developer.mozilla.org/en-US/docs/Web/CSS

https://aotu.io/notes/2019/10/29/css-preprocessor/index.html

https://zhuanlan.zhihu.com/p/36103933

https://www.w3.org/Style/CSS/current-work.en.html

https://github.com/ladjzero/ladjzero.github.io/blob/master/assets/a_brief_history_of_css.pdf

https://developer.mozilla.org/en-US/docs/Web/Houdini

https://drafts.csswg.org/css-variables-1/

https://drafts.csswg.org/css-values-4/

https://juejin.cn/post/6844904152548507661

https://engineering.fb.com/2020/05/08/web/facebook-redesign/

https://css-tricks.com/growing-popularity-atomic-css/

https://css-tricks.com/lets-define-exactly-atomic-css/

https://www.smashingmagazine.com/2013/08/other-interface-atomic-design-sass/

https://www.smashingmagazine.com/2013/10/challenging-css-best-practices-atomic-approach/

https://bradfrost.com/blog/post/atomic-web-design/

https://bradfrost.com/blog/post/atomic-design-book/

0 0 0
Share on

Alibaba Cloud Community

1,081 posts | 271 followers

You may also like

Comments

Alibaba Cloud Community

1,081 posts | 271 followers

Related Products