CSS-in-JS

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search

CSS-in-JS is a styling technique by which 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 enables the abstraction of 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 the creation of 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>

Some outcomes that may be achieved through CSS-in-JS can not be obtained using traditional CSS techniques. It is possible to make the styles dynamic in line with just a few conditional statements. Programmers may also write more modular code, with CSS being encapsulated in the same block as the programmer's JavaScript, scoping it to that module only.

Industry use[edit]

CSS-in-JS is used by Reddit, Patreon, Target, Atlassian, Vogue, GitHub and Coinbase.[citation needed]

Benefits[edit]

  • Thinking in components. It is not necessary for programmers to have to maintain a bunch of stylesheets. CSS-in-JS abstracts the CSS model to the component level, rather than the document level (modularity).
  • True rules isolation. Scoped selectors are not enough. CSS has properties that are inherited automatically from the parent element, if not explicitly defined.
  • Scoped selectors. CSS has just one global namespace; selector collisions are frequent 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 programmers don’t have to think about it.
  • Code sharing. Constants and functions may be more easily shared between JavaScript and CSS.
  • Only the styles which are currently in use on user's screens are in the DOM.
  • Dead code elimination.

References[edit]

  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.