Tables in Bootstrap

Learn how to create, style, and customize tables effectively using Bootstrap.

1. Introduction to Bootstrap Tables

Tables are used to display data in a structured format. Bootstrap makes it easy to style and customize tables for various use cases.

  • Default styles for consistent table formatting.
  • Responsive tables for mobile compatibility.
  • Interactive features like hover and striped rows.

2. Basic Table Structure

Create a simple table with .table class:

<table class="table">
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Data 1</td>
            <td>Data 2</td>
        </tr>
    </tbody>
</table>
                

3. Striped Rows

Add alternating row colors with .table-striped:

<table class="table table-striped">
    <!-- Table content -->
</table>
                

4. Bordered Tables

Add borders to table cells with .table-bordered:

<table class="table table-bordered">
    <!-- Table content -->
</table>
                

5. Hoverable Rows

Highlight rows on hover using .table-hover:

<table class="table table-hover">
    <!-- Table content -->
</table>
                

6. Small Tables

Create compact tables with .table-sm:

<table class="table table-sm">
    <!-- Table content -->
</table>
                

7. Contextual Classes

Add colors to rows or cells with contextual classes:

<tr class="table-primary"><td>Primary Row</td></tr>
<td class="table-warning">Warning Cell</td>
                

8. Responsive Tables

Make tables scrollable on smaller screens using .table-responsive:

<div class="table-responsive">
    <table class="table">
        <!-- Table content -->
    </table>
</div>
                

9. Combining Classes

Mix and match table classes for advanced styling:

<table class="table table-striped table-bordered table-hover">
    <!-- Table content -->
</table>
                

10. Sorting and Searching

Integrate JavaScript libraries like DataTables for advanced features:

// Include DataTables JavaScript
$(document).ready(function() {
    $('#example').DataTable();
});
                

11. Dark Tables

Use .table-dark for a dark-themed table:

<table class="table table-dark">
    <!-- Table content -->
</table>
                

12. Custom Table Styles

Override Bootstrap styles with custom CSS:

.table-custom {
    background-color: #f4f4f4;
    border-color: #ddd;
}
                

13. Accessibility in Tables

Ensure tables are accessible:

  • Add <caption> for descriptions.
  • Use scope="col" for headers.

14. Advanced Layouts

Create complex layouts by nesting tables:

<table class="table">
    <tr>
        <td>
            <table class="table table-sm"></table>
        </td>
    </tr>
</table>
                

15. Additional Resources