Every web developer sooner or later encounters the question of adapting tables for tablets and mobile devices. Indeed, it can be a real challenge, as table layout was not originally designed for such purposes. In the times when it was frequently used, no one could imagine that adaptation technologies would progress so far. However, we cannot completely abandon table-based layouts, as they still find their place on websites, especially in online stores. Typically, they are used for displaying order lists or product specifications. Why is that so? Well, it’s because such tables cannot be easily replaced with div elements and loops, as the backend engine may output these parameters in a loop. But then arises the question of how to make an adaptive table and avoid adding classes to all tables? There is a solution. So, let’s get started.
To begin with, you can download and see how an adaptive table works.
Explaining it in detail and boringly, I don’t see the point. Essentially, all you need to do is add styles:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
table {text-align: center;} @media only screen and (max-width: 760px), (min-device-width: 768px) and (max-device-width: 1024px) { /* Force table to not be like tables anymore */ table, thead, tbody, th, td, tr { display: block; } /* Hide table headers (but not display: none;, for accessibility) */ thead tr { position: absolute; top: -9999px; left: -9999px; } tr { border: 1px solid #ccc; } td { /* Behave like a "row" */ border: none!important; width: 100%!important; position: relative; padding-left: 50%; } td:before { /* Now like a table header */ position: absolute; /* Top/left values mimic padding */ top: 6px; left: 6px; width: 45%; padding-right: 10px; white-space: nowrap; } /* Label the data */ } |
In my version, I completely hide the table header and its names since I don’t need them. In the archive, you can see how to keep them visible; they are styled using the “before” property. And that’s all for creating an adaptive table. If you have any questions, I’m always happy to help.
2 Styling method for tables on mobile devices – introducing a horizontal scroll for scrolling.
Add the following code to your CSS file:
1 2 3 4 |
@media only screen and (max-width: 767px){ /* Tables */ table {margin: auto;border-collapse: collapse;overflow-x: auto;display: block;width: fit-content;max-width: 100%;} }ta |
Leave a Reply