Shadow DOM implementation for component style encapsulation

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    847
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    451

Implementing Shadow DOM for Component Style Encapsulation

Shadow DOM—a browser mechanism for creating an isolated DOM subtree. External styles don't penetrate inside, internal styles don't leak outside. This enables creating components that work identically in any CSS environment.

How Shadow DOM works

Document (Light DOM)
├── <header>
├── <main>
│   └── <my-widget>      ← Custom Element
│       └── #shadow-root  ← Shadow Root (encapsulation boundary)
│           ├── <style>   ← styles visible only here
│           └── <div class="widget">
│               └── <slot> ← Light DOM content projection
└── <footer>

Global CSS div { color: red } doesn't affect div inside shadow-root. CSS from shadow-root doesn't affect div outside.

Open and closed modes

// mode: 'open' — access to shadowRoot from outside (el.shadowRoot !== null)
const openShadow = element.attachShadow({ mode: 'open' })

// mode: 'closed' — shadowRoot === null from outside
// Used for maximum encapsulation (native browser elements)
const closedShadow = element.attachShadow({ mode: 'closed' })

In vast majority of cases mode: 'open' is used—dev tools, testing utilities and form management libraries (react-hook-form, browser forms) require shadowRoot access.

Styling from inside

class StyledCard extends HTMLElement {
  constructor() {
    super()
    const shadow = this.attachShadow({ mode: 'open' })

    shadow.innerHTML = `
      <style>
        /* :host — the <styled-card> element itself */
        :host {
          display: block;
          border-radius: 12px;
          overflow: hidden;
        }

        /* :host() with condition */
        :host([variant="dark"]) {
          background: #1a1a1a;
          color: #fff;
        }

        :host([variant="light"]) {
          background: #fff;
          color: #111;
          box-shadow: 0 2px 20px rgba(0,0,0,0.08);
        }

        /* :host-context() — reaction to environment */
        :host-context(.dark-theme) {
          background: #222;
        }

        .card-body {
          padding: 24px;
        }

        .card-title {
          font-size: 20px;
          font-weight: 700;
          margin: 0 0 12px;
        }

        /* ::slotted — style projected content */
        ::slotted(p) {
          margin: 0;
          line-height: 1.6;
          opacity: 0.7;
        }

        ::slotted([slot="footer"]) {
          margin-top: 20px;
          padding-top: 16px;
          border-top: 1px solid currentColor;
          opacity: 0.2;
        }
      </style>

      <div class="card-body">
        <h3 class="card-title">
          <slot name="title">Title</slot>
        </h3>
        <slot></slot>
        <slot name="footer"></slot>
      </div>
    `
  }
}

CSS Custom Properties: bridge across Shadow DOM

The only way to pass styles inside—through CSS variables. They penetrate the Shadow DOM boundary.

/* Outside: set variables */
styled-card {
  --card-bg: #f8f9fa;
  --card-radius: 16px;
  --card-padding: 32px;
  --card-title-color: #1a1a1a;
}
/* Inside Shadow DOM: use variables with fallback */
:host {
  background: var(--card-bg, #fff);
  border-radius: var(--card-radius, 8px);
}

.card-body {
  padding: var(--card-padding, 24px);
}

.card-title {
  color: var(--card-title-color, inherit);
}
<!-- Different instances with different styles -->
<styled-card style="--card-bg: #1a0050; --card-title-color: #fff">
  <span slot="title">Dark card</span>
  <p>Content</p>
</styled-card>

<styled-card style="--card-bg: #e8f5e9; --card-padding: 40px">
  <span slot="title">Green card</span>
  <p>Content</p>
</styled-card>

CSS Parts: targeted outside styling

part attribute exposes specific elements for external styles via ::part():

shadow.innerHTML = `
  <div class="wrapper" part="wrapper">
    <button class="btn" part="button trigger">
      <slot></slot>
    </button>
    <div class="dropdown" part="dropdown">
      <slot name="items"></slot>
    </div>
  </div>
`
/* Outside — style only exposed parts */
my-dropdown::part(button) {
  background: #7000ff;
  color: #fff;
  border-radius: 8px;
}

my-dropdown::part(dropdown) {
  background: #1a1a1a;
  border: 1px solid #333;
}

/* hover on part */
my-dropdown::part(button):hover {
  background: #5500cc;
}

Adoptable Stylesheets (CSSStyleSheet API)

For reusing styles between Shadow DOMs without duplication:

// Create shared stylesheet once
const sharedStyles = new CSSStyleSheet()
sharedStyles.replaceSync(`
  :host { box-sizing: border-box; }
  *, *::before, *::after { box-sizing: inherit; }

  button {
    cursor: pointer;
    border: none;
    font: inherit;
  }
`)

const typographyStyles = new CSSStyleSheet()
typographyStyles.replaceSync(`
  h1, h2, h3 { font-weight: 700; line-height: 1.2; margin: 0; }
  p { line-height: 1.6; margin: 0 0 1em; }
`)

// Use in components
class ComponentA extends HTMLElement {
  constructor() {
    super()
    const shadow = this.attachShadow({ mode: 'open' })
    // Adoptable stylesheets — no CSS duplication
    shadow.adoptedStyleSheets = [sharedStyles, typographyStyles]

    // Only component-specific styles
    const localStyle = new CSSStyleSheet()
    localStyle.replaceSync(`.wrapper { background: blue; }`)
    shadow.adoptedStyleSheets.push(localStyle)
  }
}

class ComponentB extends HTMLElement {
  constructor() {
    super()
    const shadow = this.attachShadow({ mode: 'open' })
    shadow.adoptedStyleSheets = [sharedStyles]  // only basic styles
  }
}

Shadow DOM and forms

Native form elements inside Shadow DOM don't participate in form.elements and don't end up in FormData. Solution via ElementInternals:

class CustomInput extends HTMLElement {
  static get formAssociated() { return true }

  private internals: ElementInternals
  private shadow: ShadowRoot

  constructor() {
    super()
    // formAssociated + ElementInternals allow form participation
    this.internals = this.attachInternals()
    this.shadow = this.attachShadow({ mode: 'open' })
  }

  connectedCallback() {
    this.shadow.innerHTML = `
      <style>
        input {
          width: 100%;
          padding: 10px 14px;
          border: 1px solid var(--border-color, #d0d5dd);
          border-radius: 8px;
          font: inherit;
          outline: none;
        }
        input:focus {
          border-color: var(--focus-color, #7000ff);
          box-shadow: 0 0 0 3px var(--focus-ring, rgba(112, 0, 255, 0.15));
        }
      </style>
      <input type="text" />
    `

    const input = this.shadow.querySelector('input')!
    input.addEventListener('input', () => {
      // Sync value with form
      this.internals.setFormValue(input.value)
      this.internals.setValidity(
        input.validity,
        input.validationMessage,
        input
      )
    })
  }

  // Browser calls on form reset
  formResetCallback() {
    const input = this.shadow.querySelector('input')
    if (input) input.value = ''
    this.internals.setFormValue('')
  }
}

customElements.define('custom-input', CustomInput)

Timeline

One component with Shadow DOM, Custom Properties and Parts — 1 day. System of 5–8 components with Adoptable Stylesheets, ElementInternals for forms and documentation — 1–2 weeks.