Restructure tables with media queries

Question

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.


Show source
| javascript   | html   | css   | media-queries   2017-01-04 15:01 1 Answers

Answers to Restructure tables with media queries ( 1 )

  1. 2017-01-04 16:01

    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/

Leave a reply to - Restructure tables with media queries

◀ Go back