Created
July 16, 2025 20:13
-
-
Save xemle/05094fa46f797e0a9ce7eb8fd98d59a3 to your computer and use it in GitHub Desktop.
UnoCSS Runtime in Web Component with Tailwind Reset
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>UnoCSS Runtime in Web Component with Tailwind Reset</title> | |
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@unocss/reset/tailwind.min.css" /> | |
<script src="https://cdn.jsdelivr.net/npm/@unocss/runtime"></script> | |
</head> | |
<body un-cloak class="bg-green-200"> | |
<unocss-element></unocss-element> | |
<script type="module"> | |
class UnoCssElement extends HTMLElement { | |
constructor() { | |
super() | |
this.shadow = this.attachShadow({ mode: 'open' }) | |
this.sheet = new CSSStyleSheet() | |
this.shadow.adoptedStyleSheets = [this.sheet] | |
this.uno = window.__unocss_runtime?.uno | |
this.observe() | |
this.render({color: '100', bgColor: '900'}) | |
this.animate() | |
} | |
animate() { | |
const colors = ['100', '200', '300', '400', '500', '600', '700', '800', '900'] | |
let i = 0 | |
setInterval(() => { | |
this.render({ | |
color: colors[i % colors.length], | |
bgColor: colors[(4 + i++) % colors.length] | |
}) | |
}, 400) | |
} | |
render({color, bgColor}) { | |
this.shadow.innerHTML = ` | |
<div class="p-4 m-4 bg-blue-${color} rounded shadow text-center text-lg text-yellow-${bgColor} font-bold"> | |
Hello from <code>UnoCSS</code> in a Web Component! | |
</div> | |
`; | |
} | |
observe() { | |
const observer = new MutationObserver(() => this.updateSheet()) | |
observer.observe(this.shadow, { attributes: true, childList: true, subtree: true }) | |
} | |
async updateSheet() { | |
const { css } = await this.uno.generate(this.shadow.innerHTML) | |
this.sheet.replaceSync(css) | |
} | |
} | |
customElements.define('unocss-element', UnoCssElement) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment