问题
I have the following table (jsFiddle):

<table>
<tr>
<th></th>
<th scope="col">BMW</th>
<th scope="col">Audi</th>
<th scope="col">Mercedes</th>
</tr>
<tr>
<th scope="row">GPS</th>
<td>1200</td>
<td>1000</td>
<td>1400</td>
</tr>
<tr>
<th scope="row">Bluetooth</th>
<td>700</td>
<td>750</td>
<td>680</td>
</tr>
<tr>
<th scope="row">Sensors</th>
<td>1230</td>
<td>1400</td>
<td>1100</td>
</tr>
</table>
How do I make it responsive, so that in mobile devices the table will look like this:

<table>
<tr>
<th></th>
<th scope="col">BMW</th>
</tr>
<tr>
<th scope="row">GPS</th>
<td>1200</td>
</tr>
<tr>
<th scope="row">Bluetooth</th>
<td>700</td>
</tr>
<tr>
<th scope="row">Sensors</th>
<td>1230</td>
</tr>
</table>
Is it possible to do this just in CSS? I'm guessing not since I will need to duplicate the vertical headers
回答1:
Changing the point of view and starting with three tables you can achieve the opposite effect, merging the columns when a larger viewport is available like so:
http://codepen.io/anon/pen/qEwodb
CSS
table {
border-collapse: collapse;
}
td, th {
border: 1px #ddd solid;
}
table {
margin: 20px 0;
}
td, th {
padding: 10px;
}
@media all and (min-width: 640px) {
table {
float: left;
}
table ~ table td,
table ~ table th { border-left: 0; }
table ~ table tr:first-child th:first-child { display: none; }
table ~ table tr:not(:first-child) th { display: none; }
}
With this approach the information redundancy has been kept as low as possible, since the actual data is not duplicated.
回答2:
Its Not As you wished but check this out.IT's a responsive table.
HTML
<table>
<thead>
<tr>
<th></th>
<th scope="col">BMW</th>
<th scope="col">Audi</th>
<th scope="col">Mercedes</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">GPS</th>
<td>1200</td>
<td>1000</td>
<td>1400</td>
</tr>
<tr>
<th scope="row">Bluetooth</th>
<td>700</td>
<td>750</td>
<td>680</td>
</tr>
<tr>
<th scope="row">Sensors</th>
<td>1230</td>
<td>1400</td>
<td>1100</td>
</tr>
<tbody>
</table>
CSS
table, td, th {
border: 1px solid black;
border-collapse: collapse;
padding: 0.5em;
}
@media
only screen and (max-width: 760px),
(min-device-width: 768px) and (max-device-width: 1024px) {
/* Force table to not be like tables anymore */
table, thead, tbody, th, td, tr {
display: block;
}
/* Hide table headers (but not display: none;, for accessibility) */
thead tr {
position: absolute;
top: -9999px;
left: -9999px;
}
tr { border: 1px solid #ccc; }
td {
/* Behave like a "row" */
border: none;
border-bottom: 1px solid #eee;
position: relative;
padding-left: 50%;
}
td:before {
/* Now like a table header */
position: absolute;
/* Top/left values mimic padding */
top: 6px;
left: 6px;
width: 45%;
padding-right: 10px;
white-space: nowrap;
}
/*
Label the data
*/
td:nth-of-type(1):before { content: "BMW"; }
td:nth-of-type(2):before { content: "Audi"; }
td:nth-of-type(3):before { content: "Mercedes"; }
}
DEMO
来源:https://stackoverflow.com/questions/29410762/responsive-table-with-vertical-and-horizontal-headers