How to Create Responsive Tables with Bootstrap Easily
To create a responsive table in Bootstrap, wrap your
<table> element inside a <div> with the class .table-responsive. This makes the table horizontally scrollable on small screens, ensuring it fits well on all devices.Syntax
Use a <div> with the class .table-responsive around your <table>. Inside the table, use Bootstrap classes like .table for styling.
.table-responsive: Makes the table scroll horizontally on small screens..table: Adds basic Bootstrap table styles.
html
<div class="table-responsive"> <table class="table"> <!-- table content --> </table> </div>
Example
This example shows a responsive table with some sample data. On small screens, the table will scroll horizontally instead of breaking the layout.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap Responsive Table Example</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container my-4"> <h2>Responsive Table Example</h2> <div class="table-responsive"> <table class="table table-striped table-bordered"> <thead> <tr> <th>#</th> <th>Name</th> <th>Email</th> <th>City</th> <th>Country</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Alice</td> <td>alice@example.com</td> <td>New York</td> <td>USA</td> </tr> <tr> <td>2</td> <td>Bob</td> <td>bob@example.com</td> <td>London</td> <td>UK</td> </tr> <tr> <td>3</td> <td>Charlie</td> <td>charlie@example.com</td> <td>Sydney</td> <td>Australia</td> </tr> </tbody> </table> </div> </div> </body> </html>
Output
A webpage with a styled table showing 3 rows of user data. On small screens, the table scrolls horizontally inside its container.
Common Pitfalls
One common mistake is forgetting to wrap the <table> inside a .table-responsive container, which causes the table to overflow on small screens. Another is applying .table-responsive directly to the <table> instead of a wrapping <div>. Also, not including the Bootstrap CSS link will prevent styles and responsiveness.
html
<!-- Wrong: .table-responsive applied to table --> <table class="table-responsive table"> <tr><td>Data</td></tr> </table> <!-- Right: .table-responsive wraps the table --> <div class="table-responsive"> <table class="table"> <tr><td>Data</td></tr> </table> </div>
Quick Reference
- .table-responsive: Wraps the table to enable horizontal scrolling on small devices.
- .table: Adds Bootstrap's basic table styling.
- Always include Bootstrap CSS for styles and responsiveness.
- Use
meta viewporttag for proper scaling on mobile.
Key Takeaways
Wrap your inside a