Use with Web Components

Custom Elements and Shadow DOM

This example shows how Custom Element can have its styles separated without having the side effect of polluting the root document's styles.

❗ This example is using Constructable Stylesheet Objects and DocumentOrShadowRoot.adoptedStyleSheets which have limited browser support at the moment (December 2020). The Constructible style sheets polyfill offers a solution for all modern browsers and IE 11.

import { create, cssomSheet } from 'twind'

// 1. Create separate CSSStyleSheet
const sheet = cssomSheet({ target: new CSSStyleSheet() })

// 2. Use that to create an own twind instance
const { tw } = create({ sheet })

class TwindElement extends HTMLElement {
  constructor() {
    super()

    const shadow = this.attachShadow({ mode: 'open' })

    // 3. Apply the same style to each instance of this component
    shadow.adoptedStyleSheets = [sheet.target]

    // 4. Use "own" tw function
    shadow.innerHTML = `
      <main class="${tw`h-screen bg-purple-400 flex items-center justify-center`}">
        <h1 class="${tw`font-bold text(center 5xl white sm:gray-800 md:pink-700)`}">
          This is Twind!
        </h1>
      </main>
    `
  }
}

customElements.define('twind-element', TwindElement)

document.body.innerHTML = '<twind-element></twind-element>'

🚀 live and interactive demo