【问题标题】:Set width on <td> which under <th> with colspan用 colspan 在 <th> 下的 <td> 上设置宽度
【发布时间】:2017-02-20 13:42:21
【问题描述】:

我想在tbody 中的td 上设置宽度,它位于thead 下方,colspan="2" 具有硬定义的列宽(%)。浏览器外壳不会动态调整表格宽度。

.sample {
  width: 100%;
  table-layout: fixed;
}

.sample td:nth-child(1),
.sample th:nth-child(1) {
  width: 30%;
}

.sample td:nth-child(2),
.sample th:nth-child(2) {
  width: 70%;
}
<table class="sample" border="1">
  <thead>
    <tr>
      <th colspan="2">Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>30%</td>
      <td>70%</td>
    </tr>
  </tbody>
</table>

如果thead 被删除,上述样式有效,但不适用于它。

重要提示,

  • 我添加了table-layout: fixed;,因为我需要列与指定的宽度完全相同。使用table-layoud: auto; 会导致浏览器将指定的宽度作为方向,但仍会动态调整宽度。

编辑

接受的答案解决了我上面的问题。但是我无法使用colgroup,因为我使用的是所见即所得的编辑器。因此,我添加了一个带有详细规格的后续问题here

【问题讨论】:

    标签: html css html-table


    【解决方案1】:

    尝试使用&lt;colgroup&gt;&lt;col&gt; 标签:

    .sample {
      width: 100%;
      table-layout: fixed;
    }
    <table class="sample" border="1">
      <colgroup>
        <col style="width:30%;">
        <col style="width:70%;">
      </colgroup>
      <thead>
        <tr>
          <th colspan="2">Header</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>30%</td>
          <td>70%</td>
        </tr>
      </tbody>
    </table>

    【讨论】:

      【解决方案2】:

      只需更改对我来说如此混乱的 css。将其更改为跟随

       .sample {width: 100%;}
      .sample td:nth-child(1) {width:30%;}
      .sample td:nth-child(2) {width:70%;}
      

      如果你希望这张桌子看起来不错,那么你可以给它边框,这样你就可以清楚地知道它了。

      <table class="sample" border="1px grey solid">
      ..
      </table>
      

      【讨论】:

      • 不可能!我需要固定的强制表格宽度。是的,它也让我感到困惑!
      猜你喜欢
      • 1970-01-01
      • 2013-06-17
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      相关资源
      最近更新 更多