【问题标题】:A way to group table cells together in html?一种在html中将表格单元格组合在一起的方法?
【发布时间】:2012-04-08 11:56:59
【问题描述】:

所以这很简单。我需要一种将单元格组合在一起的方法。就像 <div> 或 <span> 但它们都不起作用。 <tbody> 似乎是一个很好的解决方案,但它只适用于表格行。救命!

【问题讨论】:

  • 您是否要在<DIV> 中包装<TD> 标签?这是基本思想吗?

标签: html html-table grouping cells


【解决方案1】:

如果您正在寻找一种方法将连续的 2 个或多个单元格合并为一个单元格,以及其他“常规”单元格(如您所愿)以类似于以下方式在 google|excel 电子表格中执行):

那么您可以为td 元素使用colspan 属性,指示您要合并多少个单元格:

<tr>
  <td colspan=2> Merged Cell occupying 2 columns </td>
</tr>
<tr>
  <td> Regular cell </td>
  <td> Another cell in same row </td>
</tr>

此外,您可以在 css 中使用 td[colspan] 选择器(与您选择的任何父选择器结合使用)来引用这些合并的单元格。

这是一个工作示例:

/* Style for cells with any colspan attribute */
td[colspan] {
  text-align: center;
}

/* No extra space between cells */
table {
  border-collapse: collapse;
}

th, td {
  border: 1px solid gray;
  margin: 0;
  padding: 3px 10px;
  text-align: right;
}
<table>
  <tr>
    <th>Day</th>
    <th>Invoice</th>
    <th>Total</th>
  </tr>
  <tr>
    <!-- this cell will occupy 3 columns -->
    <td colspan=3>January</td>
  </tr>
  <tr>
    <td>2</td>
    <td>0348</td>
    <td>248.35</td>
  </tr>
  <tr>
    <td>7</td>
    <td>0349</td>
    <td>126.14</td>
  </tr>
  <tr>
    <td>18</td>
    <td>0350</td>
    <td>821.99</td>
  </tr>
  <tr>
    <td colspan=3>February</td>
  </tr>
  <tr>
    <td>27</td>
    <td>0351</td>
    <td>643.50</td>
  </tr> 
</table>

【讨论】:

    【解决方案2】:

    您可以添加 html col 标签来对列 td 进行分组。

    .col-group-1 {
      background-color: yellow;
     }
    
    .col-group-2 {
      background-color: silver;
     }
    <table>
      <colgroup>
        <col class="col-group-1">
        <col span="2" class="col-group-2">
      </colgroup>
      <tr>
        <th>Name</th>
        <th>City</th>
        <th>Phone</th>
      </tr>
      <tr>
        <td>Mary</td>
        <td>New york</td>
        <td>987654321</td>
      </tr>
      <tr>
        <td>Magdalena</td>
        <td>Los Angeles</td>
        <td>123456789</td>
      </tr>
    </table>
    
    </body>
    </html>

    请查看html col tag

    以及如何将它们与css styling一起使用

    【讨论】:

    • 不够灵活。以我的情况为例。我需要每 3 个单元格一个包装标签。如果在tr和td以上有一些标签是理想的
    • 不能只是从 W3Schools 老兄那里复制粘贴... -1
    猜你喜欢
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 2014-05-25
    • 2019-06-08
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多