转载自: 【超 Nice 的表格响应式布局小技巧 · 掘金】
思路其实比较简单:
- 利用媒体查询,设定屏幕宽度小于 600px 的样式
- 去掉原本表格的
<thead>
表头,直接隐藏即可 - 将原本的一行
<tr>
,设置为 display: block, 并且设置一个下边距,使之每一个分开 - 将原本的一行内的
<td>
,设置为 display: block,这样,它们就会竖向排列,使每一个<tr>
形成新的一个子 table
1<table>2 <caption>Lorem ipsum !</caption>3 <thead>4 <tr>5 <th>Account</th>6 <th>Due Date</th>7 <th>Amount</th>8 <th>Period</th>9 </tr>10 </thead>27 collapsed lines
11 <tbody>12 <tr>13 <td data-label="Account">Visa - 3412</td>14 <td data-label="Due Date">04/01/2016</td>15 <td data-label="Amount">$1,190</td>16 <td data-label="Period">03/01/2016 - 03/31/2016</td>17 </tr>18 <tr>19 <td scope="row" data-label="Account">Visa - 6076</td>20 <td data-label="Due Date">03/01/2016</td>21 <td data-label="Amount">$2,443</td>22 <td data-label="Period">02/01/2016 - 02/29/2016</td>23 </tr>24 <tr>25 <td scope="row" data-label="Account">Visa - 7799</td>26 <td data-label="Due Date">03/01/2016</td>27 <td data-label="Amount">$1,181</td>28 <td data-label="Period">02/01/2016 - 02/29/2016</td>29 </tr>30 <tr>31 <td scope="row" data-label="Acount">Visa - 3412</td>32 <td data-label="Due Date">02/01/2016</td>33 <td data-label="Amount">$842</td>34 <td data-label="Period">01/01/2016 - 01/31/2016</td>35 </tr>36 </tbody>37</table>
1table {2 border: 1px solid #ccc;3 border-collapse: collapse;4 margin: 0;5 padding: 0;6 width: 100%;7 table-layout: fixed;8}9
10table caption {64 collapsed lines
11 font-size: 1.5em;12 margin: .5em 0 .75em;13}14
15table tr {16 background-color: #f8f8f8;17 border: 1px solid #ddd;18 padding: .35em;19}20
21table th,22table td {23 padding: .625em;24 text-align: center;25}26
27table th {28 font-size: .85em;29 letter-spacing: .1em;30 text-transform: uppercase;31}32
33@media screen and (max-width: 600px) {34 table {35 border: 0;36 }37
38 table caption {39 font-size: 1.3em;40 }41
42 table thead {43 display: none;44 }45
46 table tr {47 display: block;48 margin-bottom: 10px;49 }50
51 table td {52 position: relative;53 border-bottom: 1px solid #ddd;54 display: block;55 font-size: .8em;56 text-align: right;57 }58
59 table td::before {60 /*61 * aria-label has no advantage, it won't be read inside a table62 content: attr(aria-label);63 */64 position: absolute;65 left: 10px;66 content: attr(data-label);67 font-weight: bold;68 text-transform: uppercase;69 }70
71 table td:last-child {72 border-bottom: 0;73 }74}