I have not found the exact example for this so please point me to a link if you have. I had also made a mistake in my prev question so I awarded a correct answer but I still need help!
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:
FROM THIS:
HEADER Data 1 HEADER Data 2 HEADER Data 3
Row 1 Data 1 Row 1 Data 2 Row 1 Data 3
Row 2 Data 1 Row 2 Data 2 Row 2 Data 3
Row 3 Data 1 Row 3 Data 2 Row 3 Data 3
TO THIS:
HEADER Data 1
Row 1 Data 1
Row 2 Data 1
Row 3 Data 1
HEADER Data 2
Row 1 Data 2
Row 2 Data 2
Row 3 Data 2
HEADER Data 3
Row 1 Data 3
Row 2 Data 3
Row 3 Data 3
To split a table into blocks of its columns is not possible with CSS. Therefore Javascript is needed. Like so:
<body>
<h1>Test</h1>
<table id="responsiveTable">
<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>
<hr>
<script>
var table = document.getElementById("responsiveTable");
var changeTable = function(e) {
if (document.body.clientWidth < 400) {
if (document.getElementById("responsiveTable")) {
var tr = null;
var td = null;
var cols = [];
for ( i=0; i<table.getElementsByTagName("tr").length; i++ ) {
tr = table.getElementsByTagName("tr")[i];
for ( j=0; j<tr.getElementsByTagName("td").length; j++) {
td = tr.getElementsByTagName("td")[j];
if(cols[j]==null) cols[j]=[];
cols[j][i] = td;
}
}
var divWrapper = document.createElement("div");
divWrapper.id = "divWrapper";
var divCol = null;
var divData = null;
for ( j=0; j<cols.length; j++ ) {
divCol = document.createElement("div");
for ( i=0; i<cols[j].length; i++ ) {
divData = document.createElement("div");
divData.innerHTML = cols[j][i].innerHTML;
divCol.appendChild(divData);
}
divWrapper.appendChild(divCol);
}
document.body.replaceChild(divWrapper, table);
}
} else if (document.getElementById("divWrapper")) {
document.body.replaceChild(table, document.getElementById("divWrapper"));
}
}
window.addEventListener("load", changeTable, true);
window.addEventListener("resize", changeTable, true);
</script>
</body>
Fiddle: http://jsfiddle.net/ch3sqx8j/
Greetings
Axel
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.