'Set maximum displayed rows count for HTML table
Have JSP page with dynamically generated HTML table with unknown number of rows.
Have property on backend, that sets maximum number of rows, e.g: max_rows=15.
How to limit number of rows for HTML table to max_rows value? Other part of table should be accessible by vertical scroll,it means that user see 15 rows and if to scroll down, that it will be seen other rows of table.
It can be done empirically by calculating average height of row and using max-height property for div-wrapper, but i think this approach is not very stable.
So it's needed to rely on row count. Perhaps there is plugin for such case or it's standard CSS or HTML solution?
Solution 1:[1]
Edit: This doesn't actually solve the problem proposed. I missed the part in the question that the user needs to be able to scroll to see the rest of rows. Whoops. So, I suppose js is actually needed.
This can actually be done without javascript. The trick is using nth-child(x):
table {
border-collapse: collapse;
}
tr:nth-child(n + 4) {
visibility: hidden;
}
The border-collapse is needed so the border doesn't extend beyond the hidden rows.
Here's the fiddle.
Solution 2:[2]
Put your table in a div block and use CSS to specify the height and overflow property of the div.
<style type="text/css">
.table_outer { height: 15em; overflow: auto; }
</style>
<div class="table_outer">
<table>
...table content...
</table>
</div>
This way the div has a fixed height and the browser will add a scrollbar when the content of the div block is too height.
I have set the height to 15em, which corresponds with 15 * font-height. When using borders, paddings and stuff this height is incorrect. But it can be calculated more properly (in px) for your design.
Solution 3:[3]
There is no way to do this with only CSS and HTML, you need javascript too. Get the height of the top 15 rows, and limit the height of a wrapping div to that height. Set overflow: auto on the div to get your scrollbars.
Don't forget to set a default height on the div as a fallback if javascript is turned off.
Solution 4:[4]
Try this:
table > tbody > tr:nth-child(n+15) {
display:none;
}
Solution 5:[5]
You can use the slice function:
$('table tbody > tr').slice(1,5).hide();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Veger |
| Solution 3 | Emil Stenström |
| Solution 4 | Kamuran Sönecek |
| Solution 5 | Andrew Myers |
