Adapt Tables To Small Screens
<table>s with many columns or long cell contents can overflow their container and cause horizontal scrolling on smaller screens. This simple technique reconfigures tabular data into a mobile friendly, single-column layout.
data attribute on each content cell stores the value of the corresponding header cell:
Along with styling to hide the header row and rearrange the structure of table elements, the values of these
data attributes are then accessed and displayed with a CSS pseudo element:
Change the width of the screen to switch layouts:
|Common Name||Scientific Name||Class||Order||Family|
|Mountain Lion||Puma Concolor||Mammalia||Carnivora||Felidae|
|Mediterranean Gecko||Hemidactylus Turcicus||Reptilia||Squamata||Gekkonidae|
|Gambel's Quail||Callipepla Gambelii||Aves||Galliformes||Odontophoridae|
Beyond this simple example, the layout and styling can be customized as desired in any number of more complex configurations including multiple columns. The
data attributes themselves can also be added and used selectively.
data attribute technique is a good solution when a
<table> is the only option. Depending on the content and desired layouts across screen sizes, in many cases a better alternative (in part, for improved accessibility) is to replace the
<table> altogether with other elements like headings and generic containers for even more layout flexibility.