Hack Frontend Community

Methods for Style Isolation in CSS

What is Style Isolation?

Style isolation is an approach to writing CSS where styles of one component don't affect other parts of the application. This is important for:

  • preventing style conflicts;
  • simplifying code scalability;
  • reusing components without side effects.

Style Isolation Methods

BEM (Block Element Modifier)

Class naming methodology ensuring uniqueness and predictability of styles.

/* BEM style */
.button {}
.button__icon {}
.button--primary {}
  • Class names describe component hierarchy.
  • Works in any CSS, without tools.

CSS Modules

.module.css (or .module.scss) files used in React/Vue/etc. provide automatic class localization.

import styles from './Button.module.css';

function Button() {
  return <button className={styles.primary}>Click</button>;
}
  • Classes transform to unique ones.
  • No intersections between components

Shadow DOM (Web Components)

Browser-level isolation — creates "shadow" DOM area hidden from external styles.

const shadow = element.attachShadow({ mode: "open" });
shadow.innerHTML = `<style>p { color: red; }</style><p>Hello</p>`;
  • Complete isolation.
  • Styles don't leak in or out.
  • Requires Web Components support.

CSS-in-JS

Styles written directly in JavaScript using libraries:

  • Styled-components
  • Emotion
  • Stitches
  • Vanilla Extract
import styled from 'styled-components';

const Button = styled.button`
  color: white;
  background: blue;
`;

Atomic CSS (Utility-first)

Using classes with specific values (Tailwind CSS).

<button class="bg-blue-500 text-white px-4 py-2">Click</button>

Recommendation:

Choose isolation method based on project scale and team preferences.