![]() | This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages)
(Learn how and when to remove this template message)
|
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.