First, I finally took the time to research this and figure out a model for my needs because I was about to gin up pagination for a table that might have anywhere from 0 to 50 rows. After a deep sigh, I decided it would be more effective to just have a simple scrollable table. At this point, let me just rant a little that a table with fixed column headings, a fixed footer and a scrollable body (rows) just SEEMS like an obvious thing. No idea why the HTML table element doesn't support this natively.
The HTML Table
<div class="row" style="border:1px solid lightgrey;padding-top:10px;max-height:500px">
<div class="col">
<div style="overflow-y:auto; max-height:350px;">
<table id="tblUserListing" style="width:100%;display:none;margin:auto;">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Login</th>
<th>Email</th>
<th>Last Login</th>
<th>Login Count</th>
<th>Status</th>
<th> </th>
</tr>
</thead>
<tbody id="tblUserListingBody" style="font-size:90%">
</tbody>
</table>
</div>
<div id="tblUserListingLoading" style="text-align:center;padding-top:20px;padding-bottom:20px">
<div class="spinner-border text-dark" role="status">
<div class="visually-hidden">loading.....</div>
</div>
</div>
</div>
</div>
This table is in the context of a lot of other stuff going on with a page that is styled by Bootstrap. As you can see, the table also doesn't have any rows in the tbody section - rows are added programmatically. However....
The DIV enclosing the table needs to support vertical scrolling and height and/or max-height. I chose a max-height so that any enclosing borders allow the table to assume its natural height up to a point... and then scroll. When the table doesn't have enough rows to fill 350px, there is no scroll bar and a properly sized border. In my case, the border is actually on a DIV a couple levels up.
The CSS
thead th {
font-weight:400;
padding-left:20px;
position:sticky;
top:0;
background-color:whitesmoke
}
This will apply to any table with thead and th elements. The critical pieces here are position: sticky; top: 0; background-color:whitesmoke. This sticks the column headers to the top of the parent DIV. The background-color is needed so that the background-color of the rows scrolling up don't bleed into the headers.
Notes
One of the great things about this approach (other than being dead simple), is that it allows the table to flow the column widths as needed based on the content of the td elements AND the headers and column data will stay aligned.

No comments:
Post a Comment