Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll table's "tbody" independent of "thead"?

As specified in the W3 specification for Tables:

Table rows may be grouped into a table head, table foot, and one or more table body sections, using the THEAD, TFOOT and TBODY elements, respectively. This division enables user agents to support scrolling of table bodies independently of the table head and foot.

I created the following example, but it doesn't work.

HTML:

<table>     <thead>         <tr>             <td>Problem</td>             <td>Solution</td>         </tr>     </thead>     <tbody>     </tbody> </table> 

JS:

$(function() {     for (var i = 0; i < 20; i++) {         var a = Math.floor(10 * Math.random());         var b = Math.floor(10 * Math.random());         var row = $("<tr>").append($("<td>").html(a + " + " + b + " ="))                            .append($("<td>").html(a + b));         $("tbody").append(row);     } }); 

CSS:

table {     background-color: #aaa; } tbody {     background-color: #ddd;     height: 100px;     overflow: auto; } td {     padding: 3px 10px; } 
like image 913
Misha Moroshko Avatar asked Nov 30 '11 06:11

Misha Moroshko


People also ask

How do I make my Tbody scrollable?

If you want tbody to show a scrollbar, set its display: block; . Set display: table; for the tr so that it keeps the behavior of a table. To evenly spread the cells, use table-layout: fixed; . Anyhow, to set a scrollbar, a display reset is needed to get rid of the table-layout (which will never show scrollbar).

Does thead have to be before Tbody?

The <thead> must appear after any <caption> or <colgroup> element, even implicitly defined, but before any <tbody> , <tfoot> and <tr> element.

What is the difference between thead and tbody?

<th> tag is used to give header in the cell of a table in HTML whereas <thead> tag is used to give the header of a group of a table.

How do I make my table body scrollable in HTML?

We set the height of the table element to 120px to make restrict the height of it so we can make it scrollable. To make it scrollable, we set the overflow CSS property to scroll . Then we set the tr elements in the thead to absolute position so they stay in place.


1 Answers

The missing part is:

thead, tbody {     display: block; } 

Demo

like image 185
bookcasey Avatar answered Oct 14 '22 20:10

bookcasey