Search code examples
javascripthtmlcssmedia-queries

Restructure tables with media queries


I have a table with four columns and two rows, as follows:

<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 media query, such as @media (max-width: 800px), I want to restructure this table to instead have two columns and four rows, e.g:

<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 this possible? Solutions in JavaScript are also welcome if, which I assume to be the case, this cannot be done with mere CSS.


Solution

  • Pure CSS

    Changing the appearance using floats and nth-child.

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

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

    JavaScript

    Looping through all applicable columns and use the modulus operator to determine where to split out into new rows.

    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/