Using Tables with Bootstrap Grids

Normally, you might say that tables and grids are mutually exclusive concepts. After all, they are both used to lay content out in rows and columns. Obviously, table is the better choice if you want to show tabular data, while grids are best used for layout. So, why would you ever want to use them together?

Let’s suppose that we want to create a table that looks like this (i.e. where each column has the exact same width):

Table with Equal Columns
Table with Equal Columns

If we add the markup and do nothing to style the table other than add Bootstrap’s .table class and apply a background colour to the header row, Chrome will display it like so:

Default Table with Minimal Styling

Not bad, but the Date column is taking up too much space.

Equal Width Columns – The CSS Way

To get equal width columns in CSS is easy:

table tr th {
  width: 25%;

This will give each of our 4 columns the same width. But if you’re already using Bootstrap in your web app, why not take advantage of its grid system and avoid having to add your own CSS?

Equal Width Columns – The Bootstrap Way

To use Bootstrap’s grids, you would normally nest rows inside of a .container element, and then place columns inside of .row elements. With tables, you don’t need to do this – the <tr> elements already serve as your rows. So the markup would look something like this:

<table class="table">
      <th class="col-md-3">Invoice</th>
      <th class="col-md-3">Date</th>
      <th class="col-md-3">Amount</th>
      <th class="col-md-3">Status</th>
      <td>Feb 1, 2014</td>
      <td>Jan 30, 2014</td>

Notice that we’ve added the column classes to the table header to avoid having to repeat them for every row. Also, by using Bootstrap’s col-md-3 class, we can divide our twelve-column grid into 4 equal parts, effectively giving each column the same width at desktop resolutions.