/

How to Make a Table Responsive Using CSS

How to Make a Table Responsive Using CSS

Tag: CSS, responsive design, mobile usability

A few days ago, I received a warning from the Google Search Console regarding a Mobile Usability issue on a page that contained a large table. Not only did this poor rendering make for a bad user experience, but it also resulted in an error in the Google Search Console. As a senior developer, I knew I had to find a solution to this problem.

After some research, I stumbled upon a helpful article on CSS Tricks titled Responsive Data Tables which provided a solution that still works today, even though it was published in 2011.

The trick to making a table responsive is to change the table’s display from the traditional CSS table to a block element. By following the steps outlined in the article, we can achieve a responsive table that displays nicely on mobile devices.

First, we hide all the table headings by moving them out of view. Then, we insert a new block in the table for each row, where each row will have its own set of headings. This can be seen in the following image:

Responsive Table Example

To implement this design, you can use the following CSS code:

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
@media only screen and (max-width: 1500px) {
table, thead, tbody, th, td, tr {
display: block;
}
thead tr {
position: absolute;
top: -9999px;
left: -9999px;
}
tr {
border: 1px solid #ccc;
}
td {
border: none;
border-bottom: 1px solid #eee;
position: relative;
padding-left: 200px;
margin-left: 150px;
}
td:before {
position: absolute;
top: 12px;
left: 6px;
width: 200px;
padding-right: 40px;
white-space: nowrap;
margin-left: -150px;
}
td:nth-of-type(1):before { content: "Option"; }
td:nth-of-type(2):before { content: "Description"; }
td:nth-of-type(3):before { content: "Type"; }
td:nth-of-type(4):before { content: "Default"; }
}

To customize this code for your own table, you will need to make changes to the last four lines. Here, you can enter the titles of each column and add or remove lines depending on the number of columns you have.

Additionally, you may need to adjust the space allocated for the new “headings” in each row. In this example, I added a 150px margin and included a margin-left: 150px in the td style and a margin-left: -150px in the td:before style.

Finally, you need to decide when this new layout becomes active. In my case, I made it active when the screen width is less than 1500px since my table is quite large. Alternatively, you could make this the default behavior, overriding the normal table display on larger screens.

I hope this solution helps you make your tables responsive and eliminates any mobile usability issues you might encounter.