首页 > 解决方案 > 了解可见性:根据 W3C 文档折叠表格列

问题描述

来自 W3C 的Dynamic rows and column effects

此折叠值会导致整个行或列从显示中移除,并且通常由行或列占用的空间可用于其他内容。

从上面我的理解是,如果我执行下面的代码片段,结果应该是这样的:

在此处输入图像描述

但相反,它显示如下:

在此处输入图像描述

table tr td {
  visibility: collapse;
}

.red {
  background-color: red;
}

/* All the below don't work as well. */

table tr td:first-child {
  visibility: collapse;
}

table colgroup col {
  visibility: collapse;
}

table colgroup {
  visibility: collapse;
} 

/* Works but I am trying to understand the why the column doesn't work as 
intended */
/* table tr {
  visibility: collapse;
} */
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<table>
  <colgroup>
    <col class="red">
    <col>
  </colgroup>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data 11</td>
      <td>Data 12</td>
    </tr>
  </tbody>
</table>
<p>Should show below the header row</p>
</body>
</html>


笔记

我也尝试过将 collapse 应用于table tr td:first-childtable colgrouptable colgroup col无济于事。但是,如果我应用折叠,table tr则该段落按预期显示在页面顶部。

此外,我知道我可以使用 实现预期结果display: none;,但我试图找出我是否误解了文档中的某些内容。此外,我在 Chrome、Firefox 和 Edge 上尝试过代码,结果都是一样的。


JSFiddle

标签: csscss-tablesw3c

解决方案


你好@ZerosAndOnes 你正在visibility: collapse;申请td。但您需要将此属性应用于tr.

visibility: collapse对于table行、列、列组和行组,行或列被隐藏,并且它们将占用的空间被删除(就像 display: none 应用于表的列/行一样) . 但是,仍会计算其他行和列的大小,就好像折叠的行或列中的单元格存在一样。此值允许从表中快速删除行或列,而无需强制重新计算整个表的宽度和高度。

table tbody tr {
  visibility: collapse;
}

.red {
  background-color: red;
}
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<table>
  <colgroup>
    <col class="red">
    <col>
  </colgroup>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data 11</td>
      <td>Data 12</td>
    </tr>
  </tbody>
</table>
<p>Should show below the header row</p>
</body>
</html>


推荐阅读