CSS-in-JS is a way to write styles directly into JavaScript code, and it is often used in conjunction with modern front-end frameworks such as React and Vue.
1. What is CSS-in-JS?
CSS-in-JS is a way of writing styles that allows developers to define styles inside JavaScript components, usually using a syntax similar to CSS. This approach improves code reusability and maintainability because it closely associates styles with component logic.
2. Choose a library
styled-components: A popular CSS-in-JS library that defines styles using template strings.emotion: Another high-performance library that supports CSS-in-JS and CSS Modules.
3. Basic usage (taking styled-components as an example)
First, install the styled-components library:
npm install styled-componentsThen, use it in your component:
import React from 'react';
import styled from 'styled-components';
const Button = styled.button`
background: ${props => props.primary ? 'blue' : 'gray'};
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
`;
function MyComponent() {
return (
<div>
<Button primary>Primary</Button>
<Button>Secondary</Button>
</div>
);
}
export default MyComponent;Code Analysis:
styled.button creates a new React component based on the button element.
CSS styles are defined in the tag template string and can contain JavaScript expressions (e.g. props.primary).
By passing the primary prop, we can change the background color of the button.
4. Advantages
- Componentization: The style is tightly coupled with the component code, which is easy to reuse and maintain.
- Dynamic styles: Styles can be dynamically generated based on component state or data.
- Avoid global scope conflicts: Each component has its own style scope, and there will be no class name conflicts.
- Type safety: When using TypeScript, static type checking can be provided.
5. Disadvantages
- Learning curve: For developers who are accustomed to traditional CSS, CSS-in-JS needs to adapt to the new syntax.
- Toolchain support: Although most modern toolchains support CSS-in-JS, debugging and some automation tasks may be more complicated than pure CSS.
- Performance: Although the library is usually optimized, it may increase the bundle size and runtime burden compared to native CSS.
6. Advanced features
- Nested selectors: Some CSS-in-JS libraries support nested selectors similar to CSS, making the code structure clearer.
const Container = styled.div`
& > .child {
margin: 10px;
}
@media (min-width: 768px) {
& > .child {
margin: 20px;
}
}
`;- CSS variables: You can define and use CSS variables (custom properties).
const ThemeProvider = styled.div`
--primary-color: blue;
`;
const Button = styled.button`
background: var(--primary-color);
`;- Composite Components: Create complex components through composition.
const StyledInput = styled.input`
/* ... */
`;
const StyledLabel = styled.label`
/* ... */
`;
const FormField = styled.div`
position: relative;
${StyledInput}, ${StyledLabel} {
/* ... */
}
`;7. Style injection and optimization
- Server-side rendering: CSS-in-JS libraries usually handle style injection for server-side rendering (SSR).
- Extract CSS: In production environments, you can configure the library to extract CSS to separate files to improve performance.
8. Integration with other libraries
- JSS: A low-level CSS-in-JS library that allows you to customize style generation strategies.
- Glamor: A lightweight library that provides a concise API.
- Emotion: In addition to CSS-in-JS, it also supports CSS Modules and style objects.
9. Practice
- Avoid excessive nesting: Keep styles concise and avoid overly complex nested structures.
- Naming conventions: Use consistent naming rules, such as BEM (Block Element Modifier).
- Component abstraction: Extract common styles into independent components to improve code reusability.
10. Code splitting and on-demand loading
Use SplitChunksPlugin (Webpack) or similar tools to load CSS-in-JS components on demand to reduce initial loading time.
11. Debugging and tools
Browser developer tools: Most CSS-in-JS libraries can be debugged in developer tools like normal CSS.
Prettier and ESLint: Configure code formatting and static analysis tools to keep your code clean.



