Creating Responsive Tables (with a Sass Mixin)

When you need a table to display some data on a website, making that table look good on mobile is not a very fun task. However you are in luck, I have created a sass mixin for creating responsive tables. All with only css no javascript. It is also built mobile first!

How it Works

Before reading, resize the example to see what happens. It will help you to understand how this is all working.

It is actually quite simple how this works. When the table is in “mobile” all the table elements (tbody, th, td, tr, tfoot) are being redefined as a block element. The <thead> is hidden and then on each of the <td> are using the pseudo-element :before to inserts the heading that would be there.

I have styled the table to have the “heading” and data each on there on row. You could easily adjust the css to stack the heading and data on top of each other, by adjusting the width of the :before to 100%, and set the margin and padding to 0 (as well as other misc css tweaks depending on what results are desired.)

I have styled this to section off each set of data, (each <tr>). You could also zebra stripe each one easily too.

When the table returns to what a table typically would like, each of the table elements are refined to display how they are if we didn’t set them to all be block elements.

As you are integrating this into an project your going to have to adjust the styling for when the table returns to “normal” to match your existing styling for tables.

How to Use

Using this is as simple as it gets. Add an id (or unique class) to your table and in your sass “extend” the placeholder %responive-tables and use the mixin responive-tables. The mixin is where you set what the headings are in order as the appear in the head. You don’t have to make these the same as in the <thead>. In fact sometimes it would make sense to shorten them (if possible) if they are too long and it causes the text to wrap to two lines. No worries though, the styling doesn’t break if the heading or the data wrap to two lines.

HTML

<table id=“rwd-table”>
<!— html for table here —>
</table>

SCSS

Browser Support

This will work in all modern browsers and in IE9+. If you need to support IE8, I would either use a polyfill that will help IE8 understand :nth-of-type or include a iestylesheet only for ie8 that forces the table to always look the same when the viewport is small. I would recommend to go with the second because of the people who use IE8 I would be surprised if anyone uses it in anything but full screen. Going the css way the better way because just in case some is using it not in full screen, or has a very low resolution monitor, they will still be able to see the data. Plus if you include a polyfill, you are making an extra http request for something most if not all will never use.