在 Shadow DOM 中使用 Tailwind Classes

There are multiple use cases in web development when it makes sense to encapsulate part of a website and make it independent from every other element in the HTML. A good example is when you integrate an external application into your page. Let's say this example application is a chatbot.

在 Web 开发中有多种用例,需要将网站的一部分封装起来,使其独立于 HTML 中的其他所有元素。一个很好的例子是当您将外部应用程序集成到您的页面中时。假设这个示例应用程序是一个聊天机器人。

You would probably be surprised (and furious) if adding the chatbot changed your pages' overall design. However, the creators of the chatbot would feel the same if their chat window was influenced by the websites where it is integrated.

如果添加聊天机器人改变了您页面的整体设计,您可能会感到惊讶(甚至愤怒)。然而,聊天机器人的创建者如果他们的聊天窗口受到集成网站的影响,也会感到同样惊讶。

Fortunately, a concept in web development aims to solve this very problem: the shadow DOM.

幸运的是,Web 开发中的一个概念旨在解决正是这个问题:shadow DOM

In one sentence, the shadow DOM is an independent DOM tree you can attach to an element, and it will ensure that the internals of the tree are hidden from the rest of the page.

一句话来说,shadow DOM 是一个你可以附加到元素的独立 DOM 树,它会确保树内部的内容对页面的其余部分隐藏。

This also means that you can (and have to) style the internals of the shadow DOM separately as CSS outside of it has no influence on the internals.

这也意味着你必须(并且只能)单独为 shadow DOM 的内部进行样式化,因为外部的 CSS 不会影响内部。

And being a modern frontend developer, you might ask the following question:

作为一个现代前端开发者,您可能会问以下问题:

Can I use Tailwind inside the shadow DOM?

我可以在 shadow DOM 内部使用 Tailwind 吗?

Let's say this post wouldn't have been born if things were so easy. Luckily for you, I already solved this problem in my latest project, so just keep reading.

假设事情这么简单,这篇文章就不会诞生了。幸运的是,我已经在我的最新项目中解决了这个问题,所以继续阅读吧。

Using Tailwind in The Shadow DOM

在 Shadow DOM 中使用 Tailwind

There has been a long discussion on the GitHub page of TailwindCSS going on for 4 years already, even though it has a (suboptimal) answer at the very top.

TailwindCSS 的 GitHub 页面上已经有一个持续了 4 年的长篇讨论,尽管顶部有一个(次优的)答案。

The most recent messages are pretty similar to what I have used to solve the problem. There were two approaches coming to ...

开通本站会员,查看完整译文。

Home - Wiki
Copyright © 2011-2026 iteam. Current version is 2.150.0. UTC+08:00, 2026-02-02 03:21
浙ICP备14020137号-1 $Map of visitor$