Junior
What are the differences between CSS isolation methods?
sobes.tech AI
Answer from AI
CSS Modules, scoped CSS (in the previous specification), CSS-in-JS.
CSS Modules:
- Each
.cssfile is treated as a module. - Classes or IDs in a CSS file are transformed into unique names (usually hashed).
- To use styles in a component, import the CSS module and use the classes as properties of the imported object.
Example of CSS Module:
/* styles.module.css */
.button {
background-color: blue;
color: white;
}
// Component.js
import styles from './styles.module.css';
function Component() {
return <button className={styles.button}>Click me</button>;
}
Scoped CSS (deprecated specification, but principles are used in frameworks):
- Styles inside
<style scoped>elements applied only to their parent element and its descendants. - Not supported in pure browsers anymore. Modern frameworks (like Vue) implement similar functionality.
Example of Scoped CSS (conceptual):
<template>
<div class="container">
<p>Text</p>
</div>
</template>
<style scoped>
.container {
border: 1px solid black;
}
p {
color: red;
}
</style>
CSS-in-JS:
- Styles are written directly in JavaScript or TypeScript code.
- Various libraries exist (e.g., styled-components, Emotion).
- Styles can be bound to components, providing automatic isolation and dynamic styles.
Example of CSS-in-JS (styled-components):
import styled from 'styled-components';
const Button = styled.button`
background-color: blue;
color: white;
`;
function Component() {
return <Button>Click me</Button>;
}
Comparison of methods:
| Method | Where styles are written | Isolation | Dependencies | Dynamic styles |
|---|---|---|---|---|
| CSS Modules | Separate .css files |
Class name transformation | Module bundler (Webpack, Parcel) | Limited (via classes) |
| Scoped CSS | <style scoped> in HTML/components |
Browser (deprecated), frameworks | None (plain CSS), or built into framework | Limited |
| CSS-in-JS | In JS/TS code | CSS-in-JS library | CSS-in-JS library | Full (JS capabilities) |