首页 > 解决方案 > 如果宽度溢出容器,则将列包装在表格中

问题描述

如果表格的宽度溢出容器,我想创建一个响应式 HTML 表格,该表格将列包裹在其下方。它应该如下所示:

默认表设计

当它被包裹起来时,它应该是这样的:

在此处输入图像描述

这个问题的最佳解决方案是什么?不使用javascript可以解决吗?

默认外观的表格在这里:

table {
    width: 100%;
    border-spacing: 0;
    border-collapse: collapse;
}

table th,
table td {
    border-top: 1px solid #edf2f9;
    border-bottom: 1px solid #edf2f9;
    padding: 10px;
    text-align: left;
}

table th {
    background: #f9fbfd;
    font-size: 10pt;
    text-transform: uppercase;
    font-weight: 400;
}
<table>
  <thead>
    <tr>
      <th>First column</th>
      <th>Second column</th>
      <th>Third column</th>
      <th>Fourth column</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>First column data 1</td>
      <td>Second column data 1</td>
      <td>Third column data 1</td>
      <td>Fourth column data 1</td>
    </tr>
    <tr>
      <td>First column data 2</td>
      <td>Second column data 2</td>
      <td>Third column data 2</td>
      <td>Fourth column data 2</td>
    </tr>
    <tr>
      <td>First column data 3</td>
      <td>Second column data 3</td>
      <td>Third column data 3</td>
      <td>Fourth column data 3</td>
    </tr>
  </tbody>
</table>

标签: javascripthtmlcss

解决方案


没有脚本,只有一种出路——媒体查询并为表格行设置“display:flex”和“flex-direction:column”属性。

table {
  width: 100%;
  border-spacing: 0;
  border-collapse: collapse;
}

table th,
table td {
  border-top: 1px solid #edf2f9;
  border-bottom: 1px solid #edf2f9;
  padding: 10px;
  text-align: left;
}

table th {
  background: #f9fbfd;
  font-size: 10pt;
  text-transform: uppercase;
  font-weight: 400;
}

@media (max-width: 800px) {
  tr {
    display: flex;
    flex-flow: column nowrap;
  }
}
<table>
  <thead>
    <tr>
      <th>First column</th>
      <th>Second column</th>
      <th>Third column</th>
      <th>Fourth column</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>First column data 1</td>
      <td>Second column data 1</td>
      <td>Third column data 1</td>
      <td>Fourth column data 1</td>
    </tr>
    <tr>
      <td>First column data 2</td>
      <td>Second column data 2</td>
      <td>Third column data 2</td>
      <td>Fourth column data 2</td>
    </tr>
    <tr>
      <td>First column data 3</td>
      <td>Second column data 3</td>
      <td>Third column data 3</td>
      <td>Fourth column data 3</td>
    </tr>
  </tbody>
</table>

这种方法不是 100% 正确,也不能完全解决问题,但目前还没有其他选择。


推荐阅读