- Published on
Tailwind CSS Table with Fixed Header and Scrollable Tbody
- Authors
- Name
- Ripal & Zalak
Tailwind CSS Table with Fixed Header and Scrollable Tbody
When working with large tables in Tailwind CSS, a common issue is keeping the table header fixed while allowing the body to scroll. This helps improve readability and user experience, especially on long datasets.
Solution
The key is to wrap the <table>
inside a div
container with overflow-y-auto
for vertical scrolling. Additionally, set position: sticky
and top: 0
on the <thead>
to keep the header fixed.
Code Implementation
<script src="https://cdn.tailwindcss.com"></script>
<div class="container mx-auto p-4">
<h1 class="mb-4 text-2xl font-bold">Tailwind CSS Table with Fixed Header</h1>
<div class="max-h-96 overflow-y-auto rounded-lg border shadow-md">
<table class="w-full border-collapse">
<thead class="sticky top-0 bg-gray-200">
<tr>
<th class="border px-6 py-3 text-left">Select</th>
<th class="border px-6 py-3 text-left">Company</th>
<th class="border px-6 py-3 text-left">Address</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-300 bg-white">
<tr class="hover:bg-gray-100">
<td class="border px-6 py-3"><input type="checkbox" /></td>
<td class="border px-6 py-3 font-semibold">BATHURST</td>
<td class="border px-6 py-3">123 Street, City</td>
</tr>
<tr class="hover:bg-gray-100">
<td class="border px-6 py-3"><input type="checkbox" /></td>
<td class="border px-6 py-3 font-semibold">MUDGEE</td>
<td class="border px-6 py-3">456 Avenue, City</td>
</tr>
<tr class="hover:bg-gray-100">
<td class="border px-6 py-3"><input type="checkbox" /></td>
<td class="border px-6 py-3 font-semibold">TAREN POINT</td>
<td class="border px-6 py-3">789 Road, City</td>
</tr>
</tbody>
</table>
</div>
</div>
Key Takeaways
- Fixed Header: The
thead
is made sticky usingsticky top-0
. - Scrollable Body: The
div
containing the table hasmax-h-96 overflow-y-auto
. - Border Styling: The table uses Tailwind utility classes for better structure and readability.
FAQs
How do I make the table fully responsive?
Ensure the parent container is overflow-x-auto
for horizontal scrolling on smaller screens.
<thead>
not staying fixed?
Why is my Make sure the <table>
is inside a div
with a defined height and overflow-y-auto
. Also, avoid display: block
on thead
.
Can I customize the header background?
Yes, change bg-gray-200
in <thead>
to any Tailwind background color class.