我有一个简单的 HTML 表格,其中
table-layout
设置为 auto
。该表有一些常规数据列,最后有一个特殊的操作列,即内部有一些按钮的列。
我现在希望我的表将可用空间简单地平均分配给所有列,除了最后一列。我希望这个操作列占用所需的最少可用空间,所有剩余空间可以在剩余表之间平均分配。
但是我还没有能够实现这一点。我无法使用此操作列的固定按钮,按钮的数量预先未知。我只需要它来自动获取最少的可用宽度,而不是通过定义显式宽度。
下面是一个最小的可重现示例。它有 4 列 (3+1)。期望的结果是最后一个应该尽可能小。
table {
width: 100%;
table-layout: auto;
/* wether it be 'auto' or 'fixed', last column should not be larger than necessary */
}
tr {
text-align: left;
}
th:last-of-type {
max-width: max-content;
background-color: orange;
}
td:last-of-type {
background-color: yellow;
max-width: max-content;
/* Does not work */
}
<table>
<tr>
<th> Header 1 </th>
<th> Header 2 </th>
<th> Header 3 </th>
<th> Actions </th>
</tr>
<tr>
<td> Data1_1 </td>
<td> Data1_2 </td>
<td> Data1_3 </td>
<td>
<button>Button 1</button>
</td>
</tr>
<tr>
<td> Data2_1 </td>
<td> Data2_2 </td>
<td> Data2_3 </td>
<td>
<button>Button 1 </button>
<button>Button 2</button>
</td>
</tr>
</table>
CSS-Grid/
subgrid
可以做到这一点,而不是表格。
保持基本相同的结构,但替换为
div
和 span
元素。
.wrap {
display: inline-grid;
grid-template-columns: repeat(3, 1fr) auto;
background: orange;
gap: .25em;
}
.row {
display: grid;
grid-template-columns: subgrid;
grid-column: 1 /-1;
}
span {
padding: .25em;
outline: 1px solid green;
display: flex;
align-items: center;
background: lightgreen;
}
button {
margin-right: .25em;
}
div {
background: lightblue;
border: 1px solid blue;
padding: .25em;
}
<div class="wrap">
<div class="row">
<span> Header 1 </span>
<span> Header 2 </span>
<span> Header 3 </span>
<span> Actions </span>
</div>
<div class="row">
<span> Data1_1 </span>
<span> Data1_2 </span>
<span> Data1_3 </span>
<span>
<button>Button 1</button>
</span>
</div>
<div class="row">
<span> Data2_1 </span>
<span> Data2_2 </span>
<span> Data2_3 </span>
<span>
<button>Button 1 </button>
<button>Button 2</button>
</span>
</div>
</div>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
width: 100%;
table-layout: auto;
/* wether it be 'auto' or 'fixed', last column should not be larger than necessary */
}
tr {
text-align: left;
}
th:last-of-type {
max-width: max-content;
background-color: orange;
}
td:last-of-type {
background-color: yellow;
max-width: max-content;
/* Does not work */
}
.action-column {
width: 25%;
}
</style>
</head>
<body>
<table>
<tr>
<th> Header 1 </th>
<th> Header 2 </th>
<th> Header 3 </th>
<th class="action-column"> Actions </th>
</tr>
<tr>
<td> Data1_1 </td>
<td> Data1_2 </td>
<td> Data1_3 </td>
<td>
<button>Button 1</button>
</td>
</tr>
<tr>
<td> Data2_1 </td>
<td> Data2_2 </td>
<td> Data2_3 </td>
<td>
<button>Button 1 </button>
<button>Button 2</button>
</td>
</tr>
</table>
</body>
</html>
实现所需功能的一种方法是设置最后一列的宽度,使其仅占据该空间。 **
所做的更改:我刚刚将第一行的最后一列指定为 25% 的特定宽度。
如果您还有任何疑问。欢迎在这篇文章下评论