Halloween Sale 15% off Ends in See the plans
HTML

Stack Tables Into Labeled Cards on Phones

On small screens, turns each row of the tables in your content into a card where every value is shown with its column heading, so wide tables can be read without sideways scrolling.

Don’t have WPIDE yet? Install it on your site

Code

<style>
@media (max-width: 600px) {
    table.wpide-stack thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
    table.wpide-stack, table.wpide-stack tbody, table.wpide-stack tr, table.wpide-stack td, table.wpide-stack th[scope="row"] { display: block; width: 100%; }
    table.wpide-stack tr { margin: 0 0 1em; border: 1px solid #ccc; border-radius: 6px; padding: .5em; }
    table.wpide-stack td { border: 0; padding: .25em 0; }
    table.wpide-stack td[data-label]::before { content: attr(data-label) ": "; font-weight: 700; }
}
</style>
<script>
(function () {
    document.querySelectorAll('.entry-content table, .wp-block-post-content table').forEach(function (table) {
        var headRow = table.tHead ? table.tHead.rows[0] : null;
        var bodyRows = table.tBodies.length ? Array.prototype.slice.call(table.tBodies[0].rows) : [];
        if (!headRow && bodyRows.length && bodyRows[0].querySelectorAll('th').length === bodyRows[0].cells.length) {
            headRow = bodyRows.shift();
            headRow.classList.add('wpide-stack-head');
        }
        if (!headRow) { return; }
        var labels = Array.prototype.map.call(headRow.cells, function (c) { return c.textContent.trim(); });
        bodyRows.forEach(function (row) {
            Array.prototype.forEach.call(row.cells, function (cell, i) {
                if (labels[i] && !cell.hasAttribute('data-label')) { cell.setAttribute('data-label', labels[i]); }
            });
        });
        table.classList.add('wpide-stack');
    });
})();
</script>

Notes

Only tables with a header row are changed; the table keeps its real structure for screen readers.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.