有没有办法根据 Tailwind 中父类的存在来显示/隐藏元素?

ner*_*ess 6 tailwind-css

有没有办法告诉 Tailwind:如果父级有某个类,则显示某个 HTML 元素,如果不隐藏它?或者这不能在 Tailwind 中完成?

<body>
  <div class="hidden">Hello</div>
</body>

<body class="show">
  <div class="block">Hello</div>
</body>
Run Code Online (Sandbox Code Playgroud)

Mar*_*hen 9

仅供参考,这一切现在都可以在 Tailwind 3 中实现。

您可以在这里找到各种修饰符:

https://tailwindcss.com/docs/hover-focus-and-other-states

一些例子:

<div class="group is-published">
  <div class="hidden group-[.is-published]:block">
    Show only when parent has class "is-published"
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

或者,如果您想在同一元素上存在某个类时添加其他类:

<div class="relative [&.active]:opacity-80">
  The class opacity-80 will actually work only when the class "active"
  is present inside the class list of the element
</div>
Run Code Online (Sandbox Code Playgroud)

甚至非常复杂的东西:

<div>
  <input type="text" class="peer" />
      <div class="hidden peer-[:nth-of-type(3)_&]:block">
        <!-- ... -->
      </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我强烈建议仔细阅读文档,因为说实话,它让我的生活变得更加轻松,我现在比制作原型之前快了 5 倍。

希望能帮助到你


Dig*_*jay -4

。Tailwind 是一个 CSS 框架。要使用条件语句,您可以将 Tailwind 与 javascript 或 php 或任何其他语言结合使用。