Jump to content

CSS-in-JS

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Koddsson (talk | contribs) at 11:54, 26 March 2021 (→‎Industry use: Add "citation needed" to unverified claim). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

CSS-in-JS is a styling technique where JavaScript is used to style components. When this JavaScript is parsed, CSS is generated (usually as a <style> element) and attached into the DOM. It allows to abstract CSS to the component level itself, using JavaScript to describe styles in a declarative and maintainable way. There are multiple implementations of this concept in the form of libraries such as

These libraries allow to create styled components using tagged template literals. For example, using styled components in a React (JavaScript library) project would look like the following:

import styled from 'styled-components';
// Create a component that renders a <p> element with blue text
const BlueText = styled.p`
  color: blue;
`;

<BlueText>My blue text</BlueText>

You can do other things using CSS-in-JS which were not possible using traditional CSS techniques. You can make the styles dynamic inline with just a few conditional statements. It also allows you to write more modular code with your CSS being encapsulated in the same block as your javascript, scoping it to that module only.

Industry use

Thousands of companies use CSS-in-JS in production, including Reddit, Patreon, Target, Atlassian, Vogue, GitHub, Coinbase, and many more.[citation needed]

Benefits

  • Thinking in components. No longer do you have to maintain a bunch of stylesheets. CSS-in-JS abstracts the CSS model to the component level, rather than the document level (modularity).
  • CSS-in-JS leverages the full power of the JavaScript ecosystem to enhance CSS.
  • True rules isolation. Scoped selectors are not enough. CSS has properties which are inherited automatically from the parent element, if not explicitly defined
  • Scoped selectors. CSS has just one global namespace. It is impossible to avoid selector collisions in non-trivial applications. CSS in JavaScript generates unique class names by default, when it compiles to CSS.
  • Vendor prefixing. The CSS rules are automatically vendor prefixed, so you don’t have to think about it.
  • Code sharing. Easily share constants and functions between JavaScript and CSS.
  • Only the styles which are currently in use on your screen are in the DOM.
  • Dead code elimination.

References

  1. ^ "Emotion - Introduction". emotion.sh. Retrieved 2019-07-03.
  2. ^ styled-components. "styled-components". styled-components. Retrieved 2019-07-03.
  3. ^ "JSS". cssinjs.org. Retrieved 2019-07-03.