Bootstrap 4 响应式 table 每列宽度具有特定宽度

Bootstrap 4 responsive table width per column to have specific width

我打算创建一个 table,其中某些列需要具有固定宽度且不能自动调整。

我试过这个方法,但没用。它似乎仍然根据文本长度自动调整宽度。

我该如何解决?

<div class="container">
    <table class="table table-bordered">
        <thead>
            <tr class="m-0">
                <th class="w-20">a</th>
                <th class="w-10">b</th>
                <th class="w-20">c</th>
                <th class="w-40">d</th>
                <th class="w-10">e</th>
            </tr>
        </thead>
        <tbody>
            <tr class="m-0">
                <th class="w-20">a. Width with 20</th>
                <th class="w-10">b. Smaller width column</th>
                <th class="w-20">c. Should be small but I'm adding the maximum text here just to test if w-20 is working.</th>
                <th class="w-40">d. Biggest width but not working!</th>
                <th class="w-10">e. Another small column</th>
            </tr>
        </tbody>
    </table>
</div>

class 在 bootstrap 中不存在,你只有 25%、50%、75% 和 100%。 你需要创建它们:

.w-20 {
  width: 20%;
}

.w-10 {
  width: 10%
}

.w-40 {
  width: 40%;
}

table {
  table-layout:fixed;/* will switch the table-layout algorythm */
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap.css" rel="stylesheet" />
<div class="container">
  <table class="table table-bordered">
    <thead>
      <tr class="m-0">
        <th class="w-20">a</th>
        <th class="w-10">b</th>
        <th class="w-20">c</th>
        <th class="w-40">d</th>
        <th class="w-10">e</th>
      </tr>
    </thead>
    <tbody>
      <tr class="m-0">
        <th class="w-20">a. Width with 20</th>
        <th class="w-10">b. Smaller width column</th>
        <th class="w-20">c. Should be small but I'm adding the maximum text here just to test if w-20 is working.</th>
        <th class="w-40">d. Biggest width but not working!</th>
        <th class="w-10">e. Another small column</th>
      </tr>
    </tbody>

  </table>
</div>

https://v4-alpha.getbootstrap.com/utilities/sizing/

Sizing

Easily make an element as wide or as tall (relative to its parent) with our width and height utilities. Includes support for 25%, 50%, 75%, and 100% by default.

https://www.w3.org/wiki/CSS/Properties/table-layout

table-layout

The table-layout property controls the algorithm used to lay out the table cells, rows, and columns.

如果需要固定宽度,请使用自定义 classes。

使用class

.w-20{ width: 200px !important; }

要在每个浏览器中都支持,最好使用以下内容:

.w-20 {
  -webkit-box-flex: 0;
  -ms-flex: 0 0 20% !important;
  flex: 0 0 20% !important;
  max-width: 20%;
}