使用CSS製作可響應的表格

一種在移動設備上以美觀方式顯示表格的實用方法 幾天前,我通過Google 搜索控制台收到了一個警告。它在我有一個大表格的頁面上檢測到了移動端可用性問題。 這是給我帶來問題的表格: 在移動設備上,它的渲染效果相當差: 這不是一種良好的用戶體驗,也是Google 搜索控制台上的問題。如果有什麼我不希望看到的就是這樣一個錯誤/警告。尤其還是我能解決的問題。 我使用的靜態網站生成器Hugo允許我將特定於單個頁面的CSS代碼注入,只需將<style>標籤添加到Markdown文件中即可。非常方便。 因此,我開始尋找一個很好的方法來使我的表格具有響應性。我找到了這篇非常好的CSS Tricks文章:Responsive Data Tables。它來自2011年,但仍然適用! 這個技巧是這樣的:我們希望將表格顯示為塊元素,而不是傳統CSS意義上的表格。我們通過將所有表格標題移到視圖之外,然後在表格中插入一個新的塊元素,每行都有自己的標題,就像這樣: 以下是實現上述設計的代碼: @media only screen and (max-width: 1500px) { table, thead, tbody, th, td, tr { display: block; } thead tr { position: absolute; top: -9999px; left: -9999px; } tr { border: 1px solid #ccc; } td { border: none; border-bottom: 1px solid #eee; position: relative; padding-left: 200px; margin-left: 150px; } td:before { position: absolute; top: 12px; left: 6px; width: 200px; padding-right: 40px; white-space: nowrap; margin-left: -150px; } td:nth-of-type(1):before { content: "Option"; } td:nth-of-type(2):before { content: "Description"; } td:nth-of-type(3):before { content: "Type"; } td:nth-of-type(4):before { content: "Default";} } 你希望自定義的重要部分是最後4行 - 你需要輸入每個“列”的標題,如果有更多列,則需要添加更多行。如果列較少,則可以將它們移除。...