Bootstrap Tutorial - Create responsive table alternative








The following code shows how to create responsive table alternative.

Example

<!-- Code revised from 
http://fiddle.jshell.net/9zVE5/5 -->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'
  src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>
<style type='text/css'>
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
table.responsive {<!--from ww  w.ja  v a 2 s. c  o m-->
  border-collapse: collapse;
}
@media only screen and (max-width: 760px) , ( min-device-width : 768px)
  and (max-device-width: 1024px) {
  table.responsive {
    width: 100%;
    min-width: 320px;
  }
  /* Force table to not be like tables anymore */
  table.responsive, table.responsive thead, table.responsive tbody, table.responsive th,
    table.responsive td, table.responsive tr {
    display: block;
  }
  /* Hide table headers (but not display: none;, for accessibility) */
  table.responsive th {
    position: absolute;
    top: -9999px;
    left: -9999px;
  }
  table.responsive tr {
    border: 1px solid #ccc;
  }
  table.responsive tr:nth-of-type(even) {
    background-color: #eee;
  }
  table.responsive td {
    /* Behave  like a "row" */
    border: none;
    border-bottom: 1px solid #eee;
    position: relative;
    padding-left: 50% !important;
  }
  table.responsive td:before {
    /* Now like a table header */
    position: absolute;
    /* Top/left values mimic padding */
    top: 6px;
    left: 6px;
    width: 45%;
    padding-right: 10px;
    white-space: nowrap;
  }
}
</style>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$(document).ready(function() {
    $("table.responsive").each(function() {
        var headers = [];
        $(this).find("th").each(function () {
            headers.push($(this).text().trim());
        });
        // Generate CSS string
        var css_str = "<style>@media only screen and (max-width: 760px), (min-device-width: 768px) and (max-device-width: 1024px) { ";
        var header, num;
        for (var i in headers) {
          header = headers[i].replace(/([\\"])/g, "\\$1").replace(/\n/g, " ");
          num = parseInt(i,10)+1;
          css_str += "table.responsive td:nth-of-type("+num+"):before { content: \""+header+"\"; }" + "\n";
        }
        css_str += " }</style>";
        $(css_str).appendTo("head");
    });
});
});//]]>  
</script>
</head>
<body>
  <table class="table table-condensed table-bordered table-striped table-hover responsive">
    <tr>
      <th align="left">Header1</th>
      <th align="left">Header2</th>
      <th align="left">Header3</th>
    </tr>
    <tr>
      <td>alpha</td>
      <td>bravo</td>
      <td>charlie</td>
    </tr>
    <tr>
      <td>ALPHA</td>
      <td>BRAVO</td>
      <td>CHARLIE</td>
    </tr>
  </table>
</body>
</html>

Click to view the demo