Responsive Tables with CSS and jQuery

One of the big problems with Responsive Web Design is dealing with fixed size elements, especially iFrames and Tables. While a table can be flexible, there will also be a minimum size past which it will spill out of it’s container or be cropped/trigger scrolling, depending on your CSS setup.

Whilst working on a site recently I started looking for a solution and came across a good round up of responsive table techniques by Chris Coyier. There are no perfect solutions, and each of the techniques there have pros and cons depending on your exact design. From a UX perspective I think Chris’ technique displaying a table as a list using pseudo elements is great – however when non-code-savvy editors will be creating your content, you can’t expect them to create custom CSS or add unusual variables to the table HTML. In the end I decided the most versatile was the second solution created by Scott Jehl that shrinks the table using CSS below a @media-query defined break and allows you to view it as an overlay. One big problem with this implementation is cross browser compatibility – there isn’t a lot of it…

The root of the problem is support for CSS :before and background oddities. So I came up with another approach based on Scott’s work. I use a bit more jQuery than he did, but it has support down to Internet Explorer 8 / Firefox 3.6. Internet Explorer 7 works but lacks the “Click here to expand” message, although this could be remedied in jQuery easily. IE6 half works, but I havent really spent any time working on this as I don’t need to for this project. One of the most important changes compared to Scott’s code if modifying the CSS of the table itself to create an overlay effect, rather than using :before to insert a pseudo element to create an overlay. This does mean that you would have to tweak the colours to suit your design rather than being a wholly plug and go solution, but I think this is a worth while trade off for browser support.

The short version:

  • Grab all tables with jQuery and get compare their width with their container’s width – if the table is wider, give it a class.
  • Use jQuery .on to add a click listener for the table and construct a version of the table as a modal window:
    • Grab the table
    • Wrap it in a div with the class overlay and add a Close link
    • Append it to the body
  • Add another .on click listener for the Close link to remove the node from the body.

See it in action / get the code

You can see the full demo on jsFiddle here. Spot and improvements? Get in touch in the comments and/or fork the jsFiddle.

4 thoughts on “Responsive Tables with CSS and jQuery”

Leave a comment