Scrollable Table Tbody
css, html, jquery
Solution
You can make the `tbody` scrollable by doing the below:
tbody {
display: block; /* mandatory because scroll only works on block elements */
}
tbody:nth-child(3) {
height: 75px; /* Just for the demo */
overflow-y: auto; /* Trigger vertical scroll */
width: 100px; /* Just for the demo */
}
Demo | Demo with Class Name
Note: If you wish you can either target the `tbody` as mentioned in the above sample or much better would be assigning it a scrollable class and doing as below:
tbody.scrollable {
height: 75px; /* Just for the demo */
overflow-y: auto; /* Trigger vertical scroll */
width: 100px; /* Just for the demo */
}
Base Idea: Base Idea is taken from Hashem's answer in this thread.
Update: The `tbody:nth-child(2)` didn't work because that selector applies the style to the 2nd child element which is also a `tbody`. In our case, it worked but it didn't have any effect because the 2nd child within the table was the first `tbody` (after the `thead`) and it had lesser contents which made the scrollbar unnecessary. When we made it to `nth-child(3)`, it worked because the 2nd `tbody` is actually the 3rd child element and had enough contents to exceed the set height and thereby triggered the scrollbar to come.
Have a look at this sample for reference. We can see that the style is not applied for the 1st element in the 2nd `div` and the 2nd element in the 1st `div` because both of them are not `p` tags (even though the CSS rule was same for both divs).
Problem
I have a table with dynamically generated data. Because of space limitation, I need to be able to make the the tbody scrollable. My table looks like this: ``` <table> <thead> <! -- This thead needs to stay in a fixed position--> <tr> <th></th> <th></th> </tr> <thead> <tbody> <! -- This tbody needs to stay in a fixed position--> <tr> <td></td> <td></td> </tr> </tbody> <tbody> <! -- This tbody needs to scroll --> <tr> <td></td> <td></td> </tr> </tbody> </table> ``` I've tried using css, but have been unsuccessful: ``` table tbody:nth-child(2) { height:500px; max-height:500px; overflow-y: scroll; } ``` My ideal solution is simple css. Any suggestions? Also, why does setting a height on a tbody not work?