如何使网格中的标题与主体对齐?

时间:2020-03-26 10:30:01

标签: 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>

1 个答案:

答案 0 :(得分:0)

您真的需要使用CSS网格吗?对我来说,使用HTML表格和CSS网格似乎有点麻烦。

如果没有,只需从CSS中的display: grid;删除table.list即可解决此问题。

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>