HTML Tables With Bootstrap 4
The table remains one of the most versatile tools when it comes to presenting data in a well formatted manner.
In this guide, we will take a look at presenting data in an HTML table and how to add some formatting and styling using bootstrap 4.
To create a basic table, we use the HTML <table> element, which is the main container element for tables in HTML.
The code below will create a table that displays basic personal information, that is: FirstName, LastName, YearOfBirth and Gender. In addition, we display the row number of the table data.
<th scope="col"> Nº </th>
<th scope="col"> First </th>
<th scope="col"> Last </th>
<th scope="col"> Year </th>
<th scope="col"> Gender </th>
<th scope="row"> 1 </th>
<td > Tadala </td>
<td> Doe </td>
<td> 2017 </td>
<td> Female </td>
<th scope="row"> 2 </th>
<td> Elon </td>
<td> Andiwa </td>
<td> 2015 </td>
<td> Male </td>
<th scope="row"> 3 </th>
<td> Tehillah </td>
<td> Tati </td>
<td> 2020 </td>
<td> Female </td>
At this stage, the table is very basic. Here is the output of the table. Pretty ugly right? Let’s add some styling to improve it.
Styling the table
Adding basic bootstrap table formatting
Add the table class to the opening tag of the HTML <table> element as below. The table class is the main bootstrap styling element of an HTML table.
Already, we can see that the table class adds so much to the table. Among them: better spacing, alignment and table borders as seen below.
Highlighting table header
Sometimes you may want the table header to stand out from the rest of the table data. One efficient way of doing it is to highlight the table header with some color.
For example, to highlight a table header with a light color, add the thead-light class to the tables <thead> element as follows.
Make table rows striped
To make alternating striped table rows, you can simply use bootstraps’ table-striped class.
<table class="table table-striped">
The table we currently have only has borders horizontal lines. You can add more borders after each column with the table-bordered class as follows:
<table class="table table-striped table-bordered">
Sometimes you do not want any border lines on your table, for this, you can use the table-borderless class on the HTML <table> element.
<table class="table table-striped table-borderless">
To highlight a table row when you hover over it, you can use the table-hover class as follows.
<table class="table table-hover table-borderless">
HTML tables are handy for presenting and formatting tabular data in a simple and efficient manner. With bootstrap 4 you have plenty of options to style and improve HTML table aesthetics.