Table RWD Css-Trick 提供了四種響應式網頁的解決方案,分為:擠壓(Squish)、捲動(Scroll)、摺疊橫列(Collapse Rows)、摺疊直行(Collapse Columns),以下簡單實作各種方式CSS方法。
Squish
形式相對來說比較簡單,針對顯示裝置的解析度,改變每個欄位長度,整體來說較無破壞原有表格之樣式,但當表格內某幾個欄位文字訊息特別多時,會造成這些欄位變得特別的長,因此影響觀看流程,使用者體驗自然不佳。這樣的表格較適合資訊量不大或每個欄位資訊量較一致資訊表。
Scroll
格式最為簡單,只要在語法中加入「overflow=”auto”」即完成,讓使用者在低解析度的裝置中自行滑動來瀏覽到所有資訊。
Table Scroll實作
HTML
<div class="table-responsive">
<table>
...
</table>
</div>
CSS
.table-responsive {
display: block;
width: 100%;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
-ms-overflow-style: -ms-autohiding-scrollbar;
}
.table-responsive table{
width:100%;
white-space: nowrap;
}
Collapse
則最接近 RWD 的設計方針,這就是上述提及的「破壞原本表格排版」的方式。在小螢幕上,直接轉換成 block 的顯示方式。不過這種摺疊的形式,一方面也挑戰著人類長久以來對於表格閱讀的認知。
Table Collapse實作
HTML
<table class="responsive-table">
<thead>
...
</thead>
<tbody>
...
</tbody>
</table>
CSS
table tr td,
table tr th {
border: 1px solid #1d1e22;
padding: 5px;
}
table {
border-collapse: collapse;
}
@media only screen and (max-width: 992px) {
table.responsive-table {
width: 100%;
border-collapse: collapse;
border-spacing: 0;
display: block;
position: relative;
/* sort out borders */
}
table.responsive-table td:empty:before {
content: �0a0;
}
table.responsive-table th,
table.responsive-table td {
margin: 0;
vertical-align: top;
}
table.responsive-table th {
text-align: left;
}
table.responsive-table thead {
display: block;
float: left;
}
table.responsive-table thead tr {
display: block;
padding: 0 10px 0 0;
}
table.responsive-table thead tr th::before {
content: �0a0;
}
table.responsive-table tbody {
display: block;
width: auto;
position: relative;
overflow-x: auto;
white-space: nowrap;
}
table.responsive-table tbody tr {
display: inline-block;
vertical-align: top;
}
table.responsive-table th {
display: block;
text-align: right;
}
table.responsive-table td {
display: block;
min-height: 1.25em;
text-align: left;
}
table.responsive-table tr {
border-bottom: none;
padding: 0 10px;
}
table.responsive-table thead {
border: 0;
border-right: 1px solid #1d1e22;
}
}