Responsive Web Tables using CSS
We have all been there when we make a data table, check it on our phone and the table is cut, we must scroll horizontal to view
The fix is not “not using tables” instead using CSS to change display property based on the screen size.
The main part here is “data-label”. We add this to every <td> so when the table collapses on mobile CSS can grab the label.
For desktop the table remains standard but once the table hits a breakpoint we break the table and turn rows into individual blocks.
This approach is effective as:
The viewers still see a valid table structure making it accessible.
It is not dependent on JS and entirely on the browser's CSS engine, so it loads instantly.
Each row becomes a card, making data more readable and each card represents the data of one row.
By default, table elements have unique display values like table-header-group or table-cell. On small screens, we override these with display: block.
It breaks the horizontal grid and forces every element from the table row to the cell to stack on top of each other.
attr(data-label); This CSS line tells the browser: "Look at the HTML for this cell, find the attribute called 'data-label', and print its text right here."
Since we hide the <thead> on mobile to save space, the user loses the context of what the numbers or text mean. This line puts the header title back inside every single cell.
We set padding-left: 50% on the cell.
We set the ::before element (the label) to position: absolute and give it a width of about 45%.
This creates a perfect two-column look inside a single row, where labels are aligned on the left and data is aligned on the right.

Comments
Post a Comment