Bootstrap 3 table, set fixed column width in px wi

2020-05-29 12:07发布

问题:

I need a table with fixed column widths in px on my Bootstrap 3 project. Every <th> in my table <table id="items" class="table table-striped table-condensed"> has style=##px but its not assigning it. I've tried adding style="width:auto; overflow: scroll;" to the table but it does't work. Also tried removig every class on my table but colums wont grow.

Please help!

回答1:

You could specify a <colgroup> section:

<table>
    <colgroup>
        <col span="1">
        <col span="1">
    </colgroup>
    ...
</table>

... and then set the width of your columns in CSS:

col {
    width:200px;
}

If you are using the bootstrap .table class on the table element, you will also need to set the width of your table to auto.

See this jsfiddle.



回答2:

Bootstrap 3 applies a width: 100% to the <table class="table">. In order to honor this, the browser will stretch cells to fill the remaining space. In Chrome 35 (I haven't tested in anything else), rules seem to be:

  1. If some columns are fixed, but not all, then the fixed column widths are honored, and the remaining width of the table is split between the remaining columns that have no specified width.

  2. If all <col> or <colgroups> have a specified (fixed) width, the browser will attempt to treat the widths like a percentage proportional to the width of the table. So if a two col's in a table have 100px, and 200px widths respectively, they may get 33% and 66% of the width respectively. This is not always the case the case though. The rules for this behavior seem to be quite complex and are probably browser-specific.

See this fiddle for a few examples and some experimentation.

http://jsfiddle.net/bzuillsmith/Nuhxj/129/



回答3:

The solution finally was to remove 'table' class from the <table>. That way you can specify de width on <th> by css or directly on its width attribute. With the table class the width of the column can't be set even specifying a <colgroup> like a suggested answer.