Create a Table with Fixed Headers and Scrollable Body using Tailwind CSS
In this article, we will learn how to create a table with fixed headers and a scrollable body using Tailwind CSS. This is useful when you have a large table, and you want the user to be able to scroll through the body without losing sight of the column headers.
Table Structure
To create a table with fixed headers and a scrollable body, we need to have two parts: a table head () and a table body (). The table head will contain the headers and will remain fixed at the top. The table body will contain the data and will be scrollable.
CSS Styling with Tailwind CSS
We will use Tailwind CSS to style our table. We need to apply the following CSS classes:
relativeto the table container for fixed headersstickyto the table head for making it fixedoverflow-y-autoto the table body for enabling vertical scrolling
Example HTML Markup
Here's an example markup with a table containing 5 columns and 10 rows of data:
| Column 1 | Column 2 | Column 3 | Column 4 | Column 5 |
|---|---|---|---|---|
| Data 1.1 | Data 1.2 | Data 1.3 | Data 1.4 | Data 1.5 |
Additional Tips
-
You can use
min-h-[300px]or a specific height to limit the height of the table body. -
Use the
w-fullclass to make the table fill its container width. -
Use
text-leftortext-centerfor alignment. -
You can customize borders using various classes such as
border,border-gray-300orborder-b.
Summary
- Divide the table into a fixed header () and scrollable body ().
-
Apply CSS classes to the parent container, headers, and body:
relative,sticky, andoverflow-y-auto. - Customize the table appearance using Tailwind CSS utility classes.