Jul 18
Tailwind CSS' "hidden" class won't hide the element!
Strange. You use Tailwind CSS and somewhere you add the Tailwind c"hidden" class - but the element just won‘t disappear!? Yes, yes. The infamous "I swear, it's hidden, but it isn't"-Tailwind mystery strikes again!
Let‘s investigate this: So, in your project, you first have the Tailwind „hidden“ class applied to some element. In HTML, hard-coded. You then remove it programmatically, and it shows up. Great. But then, you want to hide the element again, resetting your web app, and to do so you programmatically re-apply the "hidden"-class. BUT the frickin‘ element is still visible! No!
And then, to add insult to injury, when you use Firefox Inspector to check things out, the element in question actually HAS the class "hidden" applied! So why is it visible??
Let‘s quickly cut to the chase here: Let me ask you: Do you use jQuery? And do you use .show() and .hide() from its tool-chest? Well, that‘s the reason then. With Tailwind CSS you need to .addClass(„hidden“) and .removeClass(„hidden“) instead of show() and hide().
The reason: jQuery‘s show/hide toggles the CSS 'display' property, while tailwind toggles CSS 'visibility'. When you mix these up, things get out of sync and one overrides the other, resulting in an element still being visible despite one property demanding it is not.
But your mileage may vary and here are a few possibilities why an element may stay visible even after you re-apply the hidden class:
- CSS Specificity or Overriding Styles
Tailwind’s hidden sets display: none, but maybe another class or inline style is overriding that. Check the full computed style in the Inspector, not just the class list. - Animations or Transitions
If you’re using Tailwind’s animation utilities (like transition, duration, etc.), an animation might finish before hidden takes effect — or vice versa. JavaScript might need to wait for transitions to complete. - JavaScript Timing Issues
If the class is added immediately after removal, you might have a race condition or DOM update lag. Consider using setTimeout as a test:
elem.classList.remove('hidden');
setTimeout(() => {
elem.classList.add('hidden');
}, 100); - Element Positioning or Visibility
hidden only affects display, but if the element has styles like visibility: visible, opacity: 1, or position: absolute somewhere in its stack, it might still appear depending on layout. - Firefox’s DevTools Quirks
Occasionally the Inspector might show a class applied, but the layout hasn’t reflowed yet. Try forcing a layout flush:
elem.offsetHeight; // Forces reflow
In order to find out what actually is going on:
- Use Firefox’s Computed Styles tab and check display.
- Temporarily add a red border to spot the element visually even if hidden:
elem.style.border = '2px solid red'; - Try toggling other visibility classes (invisible, opacity-0) to test effects.
I hope this post helped a little.