Hiding and Showing Elements Responsively in Tailwind
Tailwind CSS provides utility classes that make it easy to hide or show elements based on screen size or other conditions without writing custom CSS or media queries.
1. Using hidden
and block
The simplest way to hide or show content:
<div class="hidden md:block">
This will only show on medium (768px+) and larger screens.
</div>
<div class="block md:hidden">
This will only show on small screens.
</div>
2. Use Other Display Values
You can use inline
, flex
, grid
, etc., instead of just block
:
<div class="hidden lg:flex">
Visible as a flexbox only on large (1024px+) screens
</div>
3. Mobile-First Hiding Strategy
Tailwind is mobile-first, so use the hidden
class as the default, and apply visibility as screens get larger:
<div class="hidden md:block">
Hidden by default, shown from md (768px) and up
</div>
4. Conditional Visibility with JS
You can toggle these classes dynamically using frameworks like Alpine.js or custom JavaScript:
<div x-data="{ open: false }">
<button @click="open = !open">Toggle Menu</button>
<div x-show="open" class="mt-2">
Menu Content
</div>
</div>
5. Best Practices
- Use
hidden
for visibility control, not for access control (users can still access hidden content via dev tools). - Avoid using
hidden
with screen readers if accessibility is a concern β prefersr-only
. - Combine with Tailwindβs responsive prefixes to reduce duplicate markup.
Conclusion
Hiding and showing elements with Tailwind is clean, efficient, and highly readable. With responsive utilities and classes like hidden
, you can build dynamic, mobile-first layouts effortlessly.