Use With
Using Twind with Custom Elements and Shadow DOM
- 📝 Inspect the example
- 📓 Consult the API reference
- 📜 Read the changelog
This guide shows how Custom Elements can have their styles separated without having the side effect of polluting the root document's styles.
In modern browsers this integration uses Constructable Stylesheet Objects and adoptedStyleSheets
for optimal performance. In legacy browsers, it falls back to using separate style elements (one per element instance) that are all kept in sync.
-
Install from npm
@twind/core
and@twind/with-web-components
are available on npm and need to be installed together.shnpm install @twind/core @twind/with-web-components
-
Define the configuration
Using an extra file,
twind.config.js
, allows some tools like IntelliSense to find your configuration.twind.config.js jsimport { defineConfig } from '@twind/core' export default defineConfig({ /* @twind/with-web-components will use * hashed class names in production by default * If you don't want this, uncomment the next line */ // hash: false, })
-
Create a Custom Element
install
creates a mixin that can be used to enhance elements with a shared stylesheet, generates styles for all used CSS classes and addsthis.tw
(the twind instance) to the element instance.The mixin function can be used with several elements — they all will share the same twind instance.
jsimport install from '@twind/with-web-components' import config from './twind.config' const withTwind = install(config) class TwindElement extends withTwind(HTMLElement) { constructor() { super() const shadow = this.attachShadow({ mode: 'open' }) shadow.innerHTML = `<h1 class="text-3xl font-bold underline">Hello world!</h1>` } } customElements.define('twind-element', TwindElement)
-
Optional: Install and configure the recommended presets
@twind/preset-autoprefix
and@twind/preset-tailwind
.Install the presets
All presets are available on npm.
shnpm install @twind/preset-autoprefix @twind/preset-tailwind
Configure the presets
Each preset must be added to the
presets
array in the configuration.twind.config.js jsimport { defineConfig } from '@twind/core' import presetAutoprefix from '@twind/preset-autoprefix' import presetTailwind from '@twind/preset-tailwind' export default defineConfig({ presets: [presetAutoprefix(), presetTailwind()], })