javascript - 如果宽度溢出容器,则将列包装在表格中
问题描述
如果表格的宽度溢出容器,我想创建一个响应式 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>
解决方案
没有脚本,只有一种出路——媒体查询并为表格行设置“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% 正确,也不能完全解决问题,但目前还没有其他选择。
推荐阅读
- reporting-services - 当报告中没有数据时,不应发送 SSRS 报告电子邮件订阅
- javascript - 设置状态方法似乎什么都不做。为什么?
- java - 从java代码设置日期和时间的问题
- django - Django hitcount order_by("hit_count_generic__hits") 在 PostgreSQL 数据库上给出错误
- javascript - 无法在 javascript 中设置已创建事件对象的属性
- javascript - conditionalPanel() 基于包含来自字符串的逻辑
- python - Python的静态数据流图生成器?
- javascript - Chart JS折线图:填充线上方而不是线下方的区域
- javascript - 反应本机选项卡导航 - 在获取完成之前阻止选项卡更改
- ruby-on-rails - 如何将 Rails 应用程序划分为逻辑部分?