- Table with max-height
- Prevent Row Break Between Pages
- Ref
Table with max-height
- Scenario: source list is too long and table is without pagination
- Pure CSS solutions:
- Solution 1
- Change display property of table to flex
- <thead /> allows no grow in height, width minus the width of scrollbar to keep the column width in form with <tbody />
- <tbody /> occupies the rest height
- Solution 2
- Change display property of table to Block
- <thead /> as sticky at top and white background color
- Small flaw: <thead /> is also inside the scroll container
// Solution 1
// HTML
<div class="table-container">
<table>
<thead>
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
</thead>
<tbody>
<tr>
<td>content1</td>
<td>content2</td>
<td>content3</td>
<td>content4</td>
</tr>
<tr>
<td>content1</td>
<td>content2</td>
<td>content3</td>
<td>content4</td>
</tr>
...
</tbody>
</table>
</div>
// CSS
.table-container {
height: 10em;
}
table {
display: flex;
flex-flow: column;
height: 100%;
width: 100%;
}
table thead {
/* head takes the height it requires,
and it's not scaled when table is resized */
flex: 0 0 auto;
width: calc(100% - 0.9em);
}
table tbody {
/* body takes all the remaining available space */
flex: 1 1 auto;
display: block;
overflow-y: scroll;
}
table tbody tr {
width: 100%;
}
table thead, table tbody tr {
display: table;
table-layout: fixed;
}
// Solution 2
<table style="display: block; height: 100px; overflow: auto;">
<thead>
<tr>
<td style="position: sticky; top: 0;">Header stays put</td>
<td style="position: sticky; top: 0;">Layout aligned</td>
</tr>
</thead>
<tbody>
<tr>
<td>foo1</td>
<td>Header stays put</td>
</tr>
<tr>
<td>foo2</td>
<td>Header stays put</td>
</tr>
</tbody>
</table>
Prevent Row Break Between Pages
@media print {
table tbody tr {
break-inside: avoid-page;
}
}
Ref
Table with max-height – solution 1
Table with max-height – solution 2