Thomas David Baker Thomas David Baker - 3 months ago 16
CSS Question

How can I make tables respect the grid in Bootstrap 3?

Bootstrap tables do not respect the grid even if they have col-xs-X classes defined.

Here's a minimal example that shows how the (red) table doesn't line up with the (gray) grid: http://jsfiddle.net/fm65v3e0/



.col-xs-1 {
background-color: #eee;
border: 1px solid #999;
}

th {
background-color: #fee;
border: 1px solid red;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row">
<div class="col-xs-1">col</div><div class="col-xs-1">col</div><div class="col-xs-1">col</div><div class="col-xs-1">col</div><div class="col-xs-1">col</div><div class="col-xs-1">col</div><div class="col-xs-1">col</div><div class="col-xs-1">col</div><div class="col-xs-1">col</div><div class="col-xs-1">col</div><div class="col-xs-1">col</div><div class="col-xs-1">col</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="table-responsive">
<table class="table">
<tr>
<th class="col-xs-5">
5-col header
</th>
<th class="col-xs-3">
3-col header
</th>
<th class="col-xs-4">
4-col header
</th>
</tr>
</table>
</div>
</div>
</div>
</div>





Because the table appears within a column it has a certain amount of padding around the outside. If I remove the padding from columns the table lines up but of course now any text inside a column will be flush against the next column.

Additionally, Bootstrap tables are 100% width by default and apportion any "spare" space if you don't use all 12 columns.

My site is almost entirely tabular data so if I don't have my tables respect the grid it's a bit like I'm not using a grid at all. Do you think I can solve this easily? Is it a mistake to try and solve it/care about this?

Dan Dan
Answer

Your bootstrap CSS adds padding-right: 15px and padding-left: 15px to all of the col-xx-xx elements.

Remove or override the padding and things should become aligned properly. The below image shows what happens in your Bootply when the padding is removed.
enter image description here

One way to override this is to create a class called no-padding like so:

.no-padding {
     padding-left: 0;
     padding-right: 0
}

and apply it to any elements where you do not want padding applied. Here's an updated JS Fiddle showing this.

Comments