首页 > 解决方案 > 如何使网格中的标题与正文对齐?

问题描述

我有以下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

解决方案


你真的需要使用 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>


推荐阅读