Search code examples
javascriptcsscss-tables

Split a table row into multiple rows if length is exceeded


I have a PHP script which returns a long row. Using that I have made a snippet here - http://jsfiddle.net/MLZEb/6/

Can you help me break the row into multiple rows rather than having a horizontal scrollbar (http://jsfiddle.net/MLZEb/)?

Currently I am using word-wrap, which makes it unreadable.

td
{
word-wrap: break-word;
}
table
{
width:100%;
table-layout:fixed;
}

Snapshot of what I'm looking for


Solution

  • Semantically speaking, breaking up your row into multiple isn't a great choice because your columns won't match up with their headers anymore. That doesn't mean you're stuck with a ghastly, unresponsive table.

    Making a table fit within a narrow (mobile) device is quite easy and requires minimal markup changes:

    http://jsfiddle.net/MLZEb/9/

    tbody, tr, th, td { display: block }
    thead { display: none }
    td:before {
        content: attr(data-label);
        display: inline-block;
        width: 6em;
        padding-right: 1em;
        vertical-align: middle;
    }
    
    td:first-child {
        background: #CCC;
    }
    

    You'll need to add the data-label attribute to your tds for this to work:

    <td data-label="ID">49251</td>
    

    If you want to fill out more horizontally for wider viewports, you could employ the use of floats on some of the columns (note that a few cells have been rearranged so that they lay out nicer):

    http://jsfiddle.net/MLZEb/10/

    table, tbody, tr, th, td { display: block; border: none }
    thead { display: none }
    td:before {
        content: attr(data-label);
        display: inline-block;
        width: 5em;
        padding-right: 1em;
        vertical-align: middle;
    }
    
    td.attrib { /* add this class to any cell that should appear on the left */
        float: left;
        clear: left;
        width: 15em;
    }