如何讓CSS HTML Table RWD方法

7 月 26, 2020 | CSS, | 0 條留言

響應式表格 CSS-Trick

表格在不同裝置上的呈現方式一直是前端開發中的一個挑戰。這篇教學將介紹四種使用 CSS-Trick 中提供的解決方案,分別是擠壓、捲動、摺疊橫列、和摺疊直行。我們將深入探討每種方法的實作,讓你能夠根據專案需求選擇最適合的方式。

擠壓(Squish)

擠壓的方式相對簡單,它根據裝置的解析度改變每個欄位的長度,整體而言較不破壞原有表格樣式。然而,當某些欄位的文字訊息特別多時,可能會使這些欄位變得特別長,影響觀看流程。因此,適合資訊量不大或每個欄位資訊量較一致的表格。

捲動(Scroll)

捲動的格式最簡單,只需要在語法中加入 overflow="auto" 即可。這讓使用者在低解析度的裝置上能夠自行滑動瀏覽所有資訊。

Table Scroll 實作

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 實作

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;
    }

    table.responsive-table td:empty:before {
        content: "\00a0";
    }

    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: "\00a0";
    }

    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;
    }
}

Demo Table Collapse

這些響應式表格的實作方式,提供了不同的選擇,可以根據專案的需要選擇最適合的方案。希望這份教學能夠幫助你更好地應對表格在不同裝置上的顯示問題。