【问题标题】:Column width when cell in first row spans multiple columns第一行中的单元格跨越多列时的列宽
【发布时间】:2015-03-10 18:44:03
【问题描述】:

当第一行中的单元格跨越多列时,如何指定具有指定宽度并使用固定表格布局的表格中的列宽?

使用以下代码,第一列获得所需的宽度100px。 3 其他列的宽度相等,这不是我想要的。如何让第 2 列的宽度为 200px,第 3 列的宽度为 400px,第 4 列的空间在仍然使用 table-layout: fixed 的同时填充剩余的空间?

<table style="width: 100%; table-layout: fixed;">
   <tr>
      <td style="width: 100px">First cell</td>
      <td colspan="3">Spanning cell</td>
   </tr>
   <tr>
      <td style="background: red">1</td>
      <td style="width: 200px; background: blue">2</td>
      <td style="width: 400px; background: green">3</td>
      <td style="background: yellow">4</td>
   </tr>
</table>

【问题讨论】:

    标签: css html html-table


    【解决方案1】:

    您可以使用colgroupcol

    <table style="width: 100%; table-layout: fixed;">
        <colgroup>
           <col style="width: 100px;">
           <col style="width: 200px;">
           <col style="width: 400px;">
        </colgroup>
       <tr>
          <td>First cell</td>
          <td colspan="3">Spanning cell</td>
       </tr>
       <tr>
          <td style="background: red">1</td>
          <td style="background: blue">2</td>
          <td style="background: green">3</td>
          <td style="background: yellow">4</td>
       </tr>
    </table>
    

    http://jsfiddle.net/07mno6r5/

    【讨论】:

    • 在这里使用colgroup 是无关紧要的,而且不合逻辑:当没有其他列时,对某些列进行分组有什么意义?重要的是 col 元素并在它们上设置宽度。
    • @JukkaK.Korpela 除非我弄错了col 仅在colgroup 中有效。 w3.org/TR/html5/tabular-data.html#the-col-element
    • 稍微补充一点,您可以根据需要省略colgroup,但它将由浏览器插入。 MDN的说法是colgroup的开始标签可以省略(奇怪的说法)developer.mozilla.org/en-US/docs/Web/HTML/Element/col
    【解决方案2】:

    您可以使用 Colgroup 将列宽设置为:

    <table style="width: 100%; table-layout: fixed;">
     <colgroup>
        <col style="width: 100px"/>
        <col style="width: 200px;"/>
        <col style="width: 400px"/>
        <col style="width: auto"/>            
      </colgroup>
      <tr>
        <td>First cell</td>
        <td colspan="3">Spanning cell</td>
       </tr>
      <tr>
        <td style="background: red">1</td>
        <td style="background: blue">2</td>
        <td style="background: green">3</td>
        <td style="background: yellow">4</td>
       </tr>
    </table>
    

    这里是一个例子:JSFiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-19
      • 2012-03-27
      • 2018-10-05
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多