Tailwind CSS:定位子元素(当你必须这样做时)
The whole point of Tailwind is applying utility classes directly to elements. Styling generic elements like p or div with descendant selectors goes against the grain—it’s the kind of thing Tailwind was designed to replace.
Tailwind 的整个重点是将实用类直接应用于元素。使用后代选择器为通用元素如 p 或 div 添加样式是违背原则的——这正是 Tailwind 设计用来替代的东西。
But sometimes you don’t have a choice. Maybe it’s content from a CMS, a third-party component, or dynamically generated HTML. You need to style elements you don’t control.
但有时你没有选择。也许这是来自 CMS 的内容,第三方组件,或动态生成的 HTML。你需要为你无法控制的元素设置样式。
Let’s be clear upfront: adding a small piece of vanilla CSS to handle this is often the simplest and most sensible solution. A dedicated stylesheet for CMS content is a perfectly valid approach. But if you’re committed to staying within Tailwind’s utility-class paradigm—or just curious about what’s possible—this post shows how you can target child elements using arbitrary variants.
我们先明确一点:添加一小段普通的 CSS 来处理这个问题通常是最简单和最合理的解决方案。为 CMS 内容创建一个专用样式表是一个完全有效的方法。但如果你坚持要在 Tailwind 的工具类范式内工作——或者只是对可能性感到好奇——这篇文章展示了如何使用任意变体来 定位 子元素。
The Problem Link to heading
问题 链接到标题
Let’s say you have a container with embedded HTML you don’t control:
假设你有一个包含嵌入 HTML 的容器,你无法控制:
<div class="cms-content">
<p>Some text with a <a href="#">link</a> in it.</p>
<ul>
<li>List item one</li>
<li>List item two</li>
</ul>
</div>
You want all links inside to have specific styling—underlines on hover, a distinct color that differs from the inherited text color, maybe a font weight. The traditional approach? Write custom CSS:
你希望所有内部链接都有特定的样式——在悬停时有下划线,与继承的文本颜色不同的独特颜色,也许还有字体粗细。传统的方法?编写自定义 CSS:
.cms-content a {
font-weight: 600;
text-decoration: none;
}
.cms-content a:hover {
text-decoration: underline;
}
.cms-content li {
list-style-type: disc;
margin-left: 1.5rem;
}
That’s a perfectly valid approach—and often the right one! A small stylesheet for CMS content is simple and maintainable. But let’s see what Tailwind offers if you want to keep everything in utility classes.
这是一种完全有效的方法——而且通常是正确的选择!为 CMS 内容创建一个小样式表简单且易于维护...