css - 如何使网格中的标题与正文对齐?
问题描述
我有以下html和css。我想在下表中实现动态列数。但是网格中的标题与其他行的列的宽度不同。任何想法?谢谢!
table.list {
border-collapse: collapse;
width: 100%;
display: grid;
grid-auto-flow: row;
grid-auto-columns: minmax(200px, max-content);
}
thead {
font-weight: bold;
}
th {
padding: 4px;
}
tbody {
overflow: auto;
}
tr {
line-height: 1.5;
border: none;
border-collapse: none;
min-height: 40px;
}
tr:nth-child(2n) td {
background-color: red;
}
tr:hover td {
background-color: pink;
}
td {
min-height: 40px;
padding: 4px;
text-align: left;
border: 1px solid black;
}
<table class="list" role="grid">
<thead>
<tr role="row">
<th role="columnheader">Date</th>
<th role="columnheader">Action</th>
<th role="columnheader">Comment</th>
<th role="columnheader">Text</th>
</tr>
</thead>
<tbody>
<tr role="row">
<td role="gridcell">Mar 20</td>
<td role="gridcell">Some action</td>
<td role="gridcell">asdasdsadasdsa</td>
<td role="gridcell">Some more text </td>
</tr>
<tr role="row">
<td role="gridcell">Mar 14</td>
<td role="gridcell">Some action</td>
<td role="gridcell">asdasdsadsadsadsa</td>
<td role="gridcell">Some more text</td>
</tr>
</tbody>
</table>
解决方案
你真的需要使用 CSS 网格吗?使用 HTML 表格和 CSS 网格对我来说似乎有点多余。
如果没有,只需display: grid;
从table.list
您的 CSS 中删除即可解决问题。
table.list {
border-collapse: collapse;
width: 100%;
grid-auto-flow: row;
grid-auto-columns: minmax(200px, max-content);
}
thead {
font-weight: bold;
}
th {
padding: 4px;
}
tbody {
overflow: auto;
}
tr {
line-height: 1.5;
border: none;
border-collapse: none;
min-height: 40px;
}
tr:nth-child(2n) td {
background-color: red;
}
tr:hover td {
background-color: pink;
}
td {
min-height: 40px;
padding: 4px;
text-align: left;
border: 1px solid black;
}
<table class="list" role="grid">
<thead>
<tr role="row">
<th role="columnheader">Date</th>
<th role="columnheader">Action</th>
<th role="columnheader">Comment</th>
<th role="columnheader">Text</th>
</tr>
</thead>
<tbody>
<tr role="row">
<td role="gridcell">Mar 20</td>
<td role="gridcell">Some action</td>
<td role="gridcell">asdasdsadasdsa</td>
<td role="gridcell">Some more text </td>
</tr>
<tr role="row">
<td role="gridcell">Mar 14</td>
<td role="gridcell">Some action</td>
<td role="gridcell">asdasdsadsadsadsa</td>
<td role="gridcell">Some more text</td>
</tr>
</tbody>
</table>
推荐阅读
- php - 如何在 PHP 上安装 Redis 扩展?
- for-loop - 从 html 源解析参数
- python-3.x - 将 DOM 元素从父级定位到祖级会产生不同的结果
- python - WTForms SelectField 返回无
- c++ - 如何私下使用 2d 矢量作为类成员来创建游戏板?
- node.js - Node Express - 在 multer 保存文件之前处理表单数据
- mysql - Spring Boot JDBC 和 MySQL 中的原子性
- oop - 方法 JavaFx TreeItem getRoot() 不可见。不是 OOP/MVC 的原因是什么?
- python - 如何使用 pandas 数据框构建人口金字塔
- pytorch - 在 PyTorch 中使用 PackedSequence 时如何处理 LSTM 层之间的丢失?