首页 > 解决方案 > 如何在 HTML 中显示最大行数并自动创建新表格?

问题描述

我的表有 2 列和许多行。用 HTML 编写表格会显示一个在另一个之下的行,并且需要滚动。

我想设置一个固定的行数(即 5 行),以便一旦达到 5 行的限制,就会在第一个表旁边显示一个“新表”(具有非常 2 个相同的列标题)。

这允许一目了然地查看所有行,避免考虑在哪里中断行。

我对此做了一个说明:https ://i.postimg.cc/ZKv16T2q/tables-illustration.jpg

我不知道该怎么做(这是 HTML、CSS 还是 JavaScript 问题?),我希望我的帖子足够清晰。

谢谢

标签: javascripthtmlcsshtml-tablerows

解决方案


reddit 的某个人给了我一个很好的答案:https ://codepen.io/anon/pen/wZoYpy

HTML

    <table class="table-col">
  <thead>
    <tr>
      <th scope="col">/</th>
      <th scope="col">Title 1</th>
      <th scope="col">Title 2</th>
    </tr>
    <tr>
      <th scope="col">/</th>
      <th scope="col">Title 1</th>
      <th scope="col">Title 2</th>
    </tr>
    <tr>
      <th scope="col">/</th>
      <th scope="col">Title 1</th>
      <th scope="col">Title 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">#1</th>
      <td>text</td>
      <td>text</td>
    </tr>
    <tr>
      <th scope="row">#2</th>
      <td>text</td>
      <td>text</td>
    </tr>
    <tr>
      <th scope="row">#3</th>
      <td>text</td>
      <td>text</td>
    </tr>
    <tr>
      <th scope="row">#4</th>
      <td>text</td>
      <td>text</td>
    </tr>
    <tr>
      <th scope="row">#5</th>
      <td>text</td>
      <td>text</td>
    </tr>
    <tr>
      <th scope="row">#6</th>
      <td>text</td>
      <td>text</td>
    </tr>
    <tr>
      <th scope="row">#7</th>
      <td>text</td>
      <td>text</td>
    </tr>
    <tr>
      <th scope="row">#8</th>
      <td>text</td>
      <td>text</td>
    </tr>
    <tr>
      <th scope="row">#9</th>
      <td>text</td>
      <td>text</td>
    </tr>
  </tbody>
</table>

CSS

.table-col {
  width: 100%;
  border-collapse: collapse;
}

.table-col thead, .table-col thead tr {
  height: 52px; /* set the header height */
  overflow: hidden;
}

.table-col thead, .table-col tbody {
  display: block;
  columns: 3 400px; /* # of columns, min column width */
}

.table-col tr {
  display: flex;
  break-inside: avoid;
}

.table-col thead th {
  background-color: #eee;
}

.table-col th {
  font-weight: bold;
  text-align: left;
}

.table-col th:first-child {
  max-width: 40px;
  text-align: center;
}

.table-col td, .table-col th {
  flex: 1;
  padding: 1em;
  border-top: 1px solid #ddd;
  word-break: break-word;
}

推荐阅读