Upgrade your web design
3232Design is a Minneapolis web design studio offering affordable high-quality communication design specializing in websites and interactive media; also producing and integrating business systems, print marketing, online marketing and brand identity design for creative professionals and small to medium-sized businesses.

Call or email today for a free consultation.

Mobile-responsive tables

show all entries...

Many mobile websites have tables, but they are usually really hard to use on mobile devices. Either the table is too wide which makes the text too small, or it's zoomed in and you can't see the entire row at once. Here's a solution that uses a combination of CSS and Javascript to create CSS styles that will take any table row and display it with its headers all in one vertical block.

When I was in the middle of making a site with a lot of product specifications, I needed a generic way to make all those tables responsive. A colleague of mine pointed me to Garrett Dimon's solution on CSS-Tricks.com, which hard-coded the table headings right in the CSS. But what to do if you don't know what they are until they are displayed on the page?

The answer is to loop through the table headers in Javascript and write out a scoped block that will dynamically generate the CSS you need to display those table headers correctly. My tweak looks like this:

        $('.div_with_unique_id_and_tables').each(function () {
            var tab = $(this);
            var table = $('table', tab);
            var th = $('th', table);
            if (th.length != 0) {
                var style = '<style>@media (max-width: 760px) {';
                th.each(function (index) {
                    var cell = $(this);
                    style += '#' + tab.attr('id') + ' td:nth-of-type(' + (index + 1) + '):before { content: "' + cell.html() + '"; } ';
                });
                style += '}</style>'
                tab.prepend(style)
            }
        });
        

The trick is in the ':nth-of-type()' selector: you can selectively apply that style to only that type. In this case, we're writing out the table header for that row into each data cell, which through CSS we've made into block-level elements instead. All I had to do was instead of hard-coding those table header values, write out each block of CSS on page load that dynamically inserts the table header html, whatever that is, into the mobile-responsive media query, scoped to the id of the table's parent div.

Easy!

Note: this doesn't work on older IE browsers. But if you're running one of those on your phone, you'e got bigger problems.

Comments

No comments yet.