Stop Bootstrap table stretching to full screen width and adding extra space to the cells

Viewed 1199

I have a table that fits on screens up to 600px. When the screen size becomes larger than 600px, the table grows to fill the screen and gives each column a lot of extra spacing on the right of each cell.

How do I remove this stop the table from growing and remove extra unwanted space so that the next column starts at the end of the largest cell from the previous column?

<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
    integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> -->

</head>
<table class="table table-dark">
  <thead>
    <tr>
      <th scope="col">Stat</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">Highest Money Reached</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr>
      <th scope="row">2</th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
    <tr>
      <th scope="row">3</th>
      <td>Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
    </tr>
  </tbody>
</table>

The code is also on this JsFiddle

1 Answers

You are using Bootstrap classes, and the Bootstrap .table sets the with of the table to width:100%;. You could remove the table class from your table HTML and that would your - however it also affects some of the styling also.

Instead, to prevent your table from stretching to the full screen width (unless it needs to), you just need to add the following to your CSS:

table.table { width:auto; }

Just make sure that this is included after your Bootstrap CSS, and don't forget to include the .table in your CSS selector to override the Bootstrap class.

Working Example:

table.table { width:auto;}
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
    integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

</head>
<table class="table table-dark">
  <thead>
    <tr>
      <th scope="col">Stat</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">Highest Money Reached</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr>
      <th scope="row">2</th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
    <tr>
      <th scope="row">3</th>
      <td>Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
    </tr>
  </tbody>
</table>

Related