Is there a way to show/hide an element based on existence of a parent class in Tailwind?

Viewed 2135

Is there a way to tell Tailwind: If a parent has a certain class then show a certain HTML element, if not hide it? Or can this not be done in Tailwind?

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

<body class="show">
  <div class="block">Hello</div>
</body>
3 Answers

No. Tailwind is a css framework. To use conditional statements, you can either use Tailwind with javascript or php or any other languages.

Yes!

You can use and arbitrary value on the parent, if you conditionally add the class it will show the children like so:

Demo: https://play.tailwindcss.com/0pCtnVrAh7

<!-- hidden -->
<div class="">
  <div class="hidden item">Hey!</div>
</div>

<!-- Show if class "[&_.item]:flex" is added-->
<div class="[&_.item]:flex">
  <div class="hidden item">Hey!</div>
</div>

<!-- Coming soon -->
<div class="group should-show">
  <div class="hidden group-[&.should-show]:block">Hey!</div>
</div>

In a future update, hopefully tailwind will allow us to use the group modifier to style based on if the group has an additional class.

Actually, there is.This is a css solution, but it can be achieved in tailwind as well:

.hidden {
display:none
}

.parent .hidden {
display:block
}
<div class="hidden">Text that doesn't show up</div>
<div class="parent">
  <div class="hidden">
    Text is visible
  </div>
</div>

html

Related