【发布时间】:2021-05-14 19:36:33
【问题描述】:
我设法使用 css-grid(无 JS)创建了一个带有折叠列的响应式表格。
我使用 2 个 CSS 变量来控制显示:--data-cols 和 --show-cols。
即如果 --data-cols: 3 但 --show-cols: 2,则网格只有 2 列,但数据仍然有 3。这通常会导致数据环绕到下一行。所以我们希望 css-grid 隐藏第三列,而不是跳过它。
诀窍是创建一个跨越所有 3 个数据列的不可见行。这似乎迫使网格有 3 列。第三列的宽度为 0,因为 grid-auto-columns: 0;
这似乎在我的测试中有效。但这感觉就像一个黑客。有没有更好的方法(不用JS)?
.itemTable {
display: flex;
justify-content: center;
--show-cols: 1;
}
.itemTable:not(.data1cols) {
--show-cols: 2;
}
.itemTable.data1cols {
--data-cols: 1;
}
.itemTable.data2cols {
--data-cols: 2;
}
.itemTable.data3cols {
--data-cols: 3;
}
.itemTable.data4cols {
--data-cols: 4;
}
.itemTable table {
margin: 6px;
border-spacing: 0 4px;
padding-left: 0;
list-style: none;
overflow: hidden;
}
/* https://www.meltajon.com/dev/how-to-use-supports-display-contents-feature-query-in-safari */
@supports (display: contents) and (caret-color: red) {
.itemTable table {
display: grid;
grid-template-columns: repeat(var(--show-cols), auto);
grid-auto-columns: 0;
}
.itemTable thead,
.itemTable tbody,
.itemTable tfoot,
.itemTable tr {
display: contents;
}
}
.itemTable thead>tr>th {
font-size: 20px;
font-weight: bold;
padding: 10px 18px 5px;
text-align: center;
}
.itemTable td {
background-color: #555555;
margin-top: 5px;
}
.itemTable tr * {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
color: #9f9697;
}
.itemTable a {
padding: 8px 10px;
display: flex;
}
.itemTable .hidden-span-row>td {
grid-column: 1 / span var(--data-cols);
margin: 0;
padding: 0;
}
/* Mobile-first: Small tablet and larger */
@media all and (min-width: 479px) {
/* workaround browser not support min() */
.itemTable:not(.data2cols):not(.data1cols) {
--show-cols: 3;
}
}
/* Mobile-first: Tablet and larger */
@media all and (min-width: 700px) {
.itemTable table {
grid-template-columns: repeat(var(--data-cols), auto);
}
}
<div class="itemTable data3cols">
<table>
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
</tbody>
<tfoot>
<tr class="hidden-span-row">
<td></td>
</tr>
</tfoot>
</table>
</div>
【问题讨论】:
-
为什么要使用 html 表格并将其声明为 css-grid?使用 css-grid 的全部原因是不使用 html 表格进行设计布局。您可以使用
:nth-child(3n + 3)选择器选择第三列中的所有列并隐藏它们。 -
感谢您观看@tacoshy 我想我正在逐步增强一张桌子,所以后备仍然是一张工作表。 nth-child() 选择器不适用于 css vars,那么我将如何使用它来隐藏未知数量的数据列?
-
好吧,开枪。我意识到我的桌子在 MS Edge 中没有倒塌。谁在使用那个浏览器?