Reputation: 4539
I have not found the exact example for this so please point me to a link if you have.
I want to make a table in HTML be responsive as follows - is it possible with CSS?
<table>
<thead>
<tr>
<td>HEADER Data 1</td>
<td>HEADER Data 2</td>
<td>HEADER Data 3</td>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
<td>Row 1 Data 3</td>
</tr>
<tr>
<td>Row 2 Data 1</td>
<td>Row 2 Data 2</td>
<td>Row 2 Data 3</td>
</tr>
<tr>
<td>Row 3 Data 1</td>
<td>Row 3 Data 2</td>
<td>Row 3 Data 3</td>
</tr>
</tbody>
</table>
On small screens I want the table responsive so that is places the data as follows:
HEADER Data 1
Row 1 Data 1
Row 1 Data 2
Row 1 Data 3
HEADER Data 2
Row 2 Data 1
Row 2 Data 2
Row 2 Data 3
HEADER Data 3
Row 3 Data 1
Row 3 Data 2
Row 3 Data 3
Upvotes: 1
Views: 145
Reputation: 156
I hope this will help in making a table responsive.
Here's a fiddle
HTML :
<table>
<thead>
<tr>
<td>Name</td>
<td>Age</td>
<td>Gender</td>
</tr>
</thead>
<tbody>
<tr>
<td>Qasim</td>
<td>23yrs</td>
<td>Male</td>
</tr>
<tr>
<td>Ali</td>
<td>19yrs</td>
<td>Male</td>
</tr>
<tr>
<td>William</td>
<td>34yrs</td>
<td>Male</td>
</tr>
</tbody>
</table>
CSS :
td{
width:100px;
}
@media (max-width: 600px) {
thead {
display: none;
}
tr{
display:grid;
border-bottom:1px solid #000000;
}
td:nth-of-type(1):before { content: "Name"; }
td:nth-of-type(2):before { content: "Age"; }
td:nth-of-type(3):before { content: "Gender"; }
td:before{
width:150px;
float:left;
}
td{
width:300px;
}
}
Upvotes: 3
Reputation: 1236
Put a copy of each header inside the corresponding row, and hide it with the CSS pseudo-selector :first-child
. Then use media query to change the layout, hide the normal headers, and display the hidden headers.
HTML:
<table>
<thead>
<tr>
<td>HEADER Data 1</td>
<td>HEADER Data 2</td>
<td>HEADER Data 3</td>
</tr>
</thead>
<tbody>
<tr>
<td>HEADER Data 1</td>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
<td>Row 1 Data 3</td>
</tr>
<tr>
<td>HEADER Data 2</td>
<td>Row 2 Data 1</td>
<td>Row 2 Data 2</td>
<td>Row 2 Data 3</td>
</tr>
<tr>
<td>HEADER Data 3</td>
<td>Row 3 Data 1</td>
<td>Row 3 Data 2</td>
<td>Row 3 Data 3</td>
</tr>
</tbody>
</table>
CSS:
tbody tr td:first-child {
display: none;
}
@media (max-width: 600px) {
thead {
display: none;
}
td {
display: block;
clear: left;
}
tbody tr td:first-child {
display: block;
}
}
Here's a fiddle.
Upvotes: 1