【问题标题】:How to remove empty space in a table cell ?如何删除表格单元格中的空白空间?
【发布时间】:2016-02-13 12:57:02
【问题描述】:

在下面的代码中,我为表格单元格设置了max-width,因此无论它们携带的内容如何,​​它们都具有相同的宽度,并且vertical-align 设置为顶部。但是正如您所见,与第二个和第三个单元格相比,第一个单元格相当长,因此在第 2-5 个和第 3-6 个表格单元格之间留下了巨大的空间。有什么办法可以去掉那个空间吗?我的意思是我希望第 5 和第 6 个单元格立即跟随上述单元格,而不是等待第 1 个单元格结束。

table tr td {
  vertical-align:top;
  max-width:90px;
  background-color: #dedede;
  color: black
}
<table>
  <tr>
    <td>this is first cell. this will be quite lengthy</td>
    <td>this is second cell</td>
    <td>this is third cell</td>
  </tr>

  <tr>
    <td>this is fouth cell</td>
    <td>this is fifth cell</td>
    <td>this is sixth cell</td>
  </tr>
</table>

【问题讨论】:

  • 我猜你在谈论类似Masonry
  • @dippas 是的,有 css 解决方案吗?
  • 您可以使用浮动&lt;div&gt; 元素而不是表格单元格来获得这种效果。

标签: html css html-table tablecell


【解决方案1】:

您想要的问题是表格设置为这样的功能,因此它可以使所有内容保持一致和有条理。如前所述,如果您希望单独的方块像不同大小的砖块一样堆叠在一起,您可能需要更多地研究砖石布局,桌子在这种情况下将无法使用,因为它不是按照这种方式构建的。

【讨论】:

    【解决方案2】:

    如果我理解正确,您并不关心单元格 5 和 6 是否与单元格 4 对齐,只要它们相互对齐并去掉那个空白空间即可。在许多情况下,使用 div 比使用表格更好,但这里有一个保留表格的解决方案。

    如果要中断行对齐,则必须创建第二个表格,因此第一个表格将包含单元格 1 和 4,第二个表格将包含单元格 2、3、5 和 6。根据您的风格,请使用display:inline-block 让表格彼此相邻,如果您希望两个表格在顶部对齐,则将它们包含在 &lt;div&gt;s(切勿使用嵌套表格)和 display:inline; vertical align:top; 中。最终结果是这样的:

    <head>
    
    <style>
    table tr td {
      vertical-align:top;
      max-width:90px;
      background-color: #dedede;
      color: black;
    }
    .talign{
    display:inline-block;
    }
    .dalign{
    display:inline;
    vertical-align:top;
    }
    </style>
    </head>
    <body>
    <div class='dalign'>
    <table class='talign'>
      <tr>
        <td>this is first cell. this will be quite lengthy</td>
      </tr>
      <tr>
        <td>this is fouth cell</td>
      </tr>
    </table>
    </div>
    <div class='dalign'>
    <table class='talign'>
      <tr>
        <td>this is second cell</td>
        <td>this is third cell</td>
      </tr>
      <tr>
        <td>this is fifth cell</td>
        <td>this is sixth cell</td>
      </tr>
    </table>
    </div>
    </body>
    

    【讨论】: