Bootstrap tables are widely used in web development to display structured data. One common challenge developers face is keeping the table header visible while scrolling through a large dataset. This guide will show you how to create a Bootstrap table with a sticky table head using practical examples.
<table class="table table-striped table-bordered"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Role</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>John Doe</td> <td>john@example.com</td> <td>Admin</td> </tr> <tr> <td>2</td> <td>Jane Smith</td> <td>jane@example.com</td> <td>Editor</td> </tr> </tbody> </table>
Wrap the table in a scrollable container and use CSS position: sticky; for the table header.
<div class="table-responsive" style="max-height: 400px; overflow-y: auto;"> <table class="table table-striped table-bordered"> <thead class="thead-dark"> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Role</th> </tr> </thead> <tbody> <tr><td>1</td><td>John</td><td>john@example.com</td><td>Admin</td></tr> <tr><td>2</td><td>Jane</td><td>jane@example.com</td><td>Editor</td></tr> <!-- More rows --> </tbody> </table> </div>
This example demonstrates a simple responsive Bootstrap table with striped rows and borders.
| ID | Name | Role | |
|---|---|---|---|
| 1 | John Doe | john@example.com | Admin |
| 2 | Jane Smith | jane@example.com | Editor |
| 3 | Michael Johnson | michael@example.com | Viewer |
<div class="table-responsive" style="max-height: 500px;"> <table class="table table-hover table-bordered"> <thead class="thead-light"> <tr> <th>Product ID</th> <th>Product Name</th> <th>Category</th> <th>Price</th> <th>Stock</th> </tr> </thead> <tbody> <tr><td>101</td><td>Laptop</td><td>Electronics</td><td>$1200</td><td>15</td></tr> <tr><td>102</td><td>Smartphone</td><td>Electronics</td><td>$800</td><td>25</td></tr> <!-- More rows --> </tbody> </table> </div>
Yes, sticky headers work on modern mobile browsers. Wrapping the table in .table-responsive ensures proper scrolling and visibility.
Sticky headers work with Bootstrap 4 and 5 because they rely on CSS position: sticky rather than a specific Bootstrap class.
Adddingly. position: sticky; left: 0; to the first <th> or <td> in each row and adjust z-index accor
Fixed positions an element relative to the viewport. Sticky keeps it relative until scrolling passes a threshold. Sticky is preferred for tables.
Using a sticky table head in Bootstrap improves user experience and readability, especially for large datasets. By combining Bootstrap table classes with CSS sticky positioning, you can create responsive, professional tables for dashboards, reports, and data-heavy web apps.
Copyrights © 2024 letsupdateskills All rights reserved