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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.