jx12345
jx12345

Reputation: 1670

Bootstrap 3 tables column width control

I have a bootstrap table as follows:

<table class="table table-bordered">
  <thead>
    <tr>
      <th>Col1</th>
      <th>Col2</th>
    </tr>
  </thead>
  <tbody>  
    <tr>
      <td>test</td>
      <td>test</td>
    </tr>
  </tbody>
</table>

The two column are equally spaced which is fine but if i drop an <input> element in to one of the columns this column stretches to take up about 3/4 of the overall table.

http://www.bootply.com/115049

My question is why does it do this and how can I control it?

Any help much appreciated.

Upvotes: 1

Views: 4463

Answers (3)

Olly Hodgson
Olly Hodgson

Reputation: 15793

This is down to the way HTML tables work. By default, table cells will scale according to their contents - any size you give them is used as a guide. So, for instance:

td {
    width: 50%; 
    /* 
       If this cell is empty, it will take up half of 
       the table. But if the content needs to, it will 
       expand to take up more space. 
    */
}

You can work around this by setting table-layout: fixed; in your CSS:, e.g.

table.fixed {
    table-layout: fixed;
}

This makes tables adhere more strictly to the dimensions you set in CSS, rather than what the content dictates. See https://developer.mozilla.org/en-US/docs/Web/CSS/table-layout for more information.

Once this is done, you can apply the normal Bootstrap grid classes to control the width. Apply them to the cells (td or th) in the first row and they'll repeat all the way down.

Upvotes: 3

Tiffado
Tiffado

Reputation: 452

Why ? I don't know :)

How to control it ? You can simply but a width parameter to your td, such as :

<td width=50%><input type="text"></td>

You can do it like this, or using your css file by saying all from this class should take half of the table width.

td {
    width: 50%;
}

Upvotes: 0

<table class="table table-bordered">
<thead>
<tr>
  <th class="col-md-10">Col1</th>
  <th class="col-md-2">Col2</th>
</tr>
</thead>
<tbody>  
<tr>
  <td>test</td>
  <td>test</td>
</tr>
</tbody>
</table>

Upvotes: 4

Related Questions