Restructuring tables with the media

I have a table with four columns and two rows:

<table>
<tr>
    <td> A </td>
    <td> B </td>
    <td> C </td>
    <td> D </td>
</tr>
<tr>
    <td> E </td>
    <td> F </td>
    <td> G </td>
    <td> H </td>
</tr>
</table>

Using a query media, for example @media (max-width: 800px), I want to restructure this table to instead have two columns and four rows, for example:

<table>
<tr>
    <td> A </td>
    <td> B </td>
</tr>
<tr>
    <td> C </td>
    <td> D </td>
</tr>
<tr>
    <td> E </td>
    <td> F </td>
</tr>
<tr>
    <td> G </td>
    <td> H </td>
</tr>
</table>

Is it possible? JavaScript solutions are also welcome if, I believe, this cannot be done with simple CSS.

+4
source share
1 answer

Pure CSS

Change appearance with floatand nth-child.

td { float:left; display:inline-block; }
td:nth-child(3) {
  clear:both;
}

https://jsfiddle.net/hks5d6th/2/

Javascript

, , .

var table = document.getElementsByTagName('table')[0],
  columns = Array.prototype.slice.call(document.getElementsByTagName('td')),
  newTable = document.createElement('table'), html;

columns.forEach(function(next, idx) {
  if (idx % 2 === 0 || idx === 0) {
    html += '<tr>' + next.outerHTML;
    return;
  }
  html += next.outerHTML + '</tr>';
});

newTable.innerHTML = html;
table.replaceWith(newTable);

https://jsfiddle.net/hks5d6th/1/

+2

Source: https://habr.com/ru/post/1665749/


All Articles