CSS-Only Scrollable Table with Fixed Headers
This question calls for a CSS-only solution to create scrollable tables with fixed headers. The requirements for this solution include:
Solution Using Position: Sticky
One possible solution involves using the position: sticky property. Here's how it works:
Use of position: sticky
Sticky positioning assigns an element to a relative position except that the offset is computed concerning the nearest ancestor with a scrolling box or the viewport if there is no such ancestor. This behavior is ideal for fixed table headers.
The Code
The following code demonstrates this technique:
div { display: inline-block; height: 150px; overflow: auto } table th { position: -webkit-sticky; position: sticky; top: 0; } /* == Just general styling, not relevant :) == */ table { border-collapse: collapse; } th { background-color: #1976D2; color: #fff; } th, td { padding: 1em .5em; } table tr { color: #212121; } table tr:nth-child(odd) { background-color: #BBDEFB; }
<div> <table border="0"> <thead> <tr> <th>head1</th> <th>head2</th> <th>head3</th> <th>head4</th> </tr> </thead> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> <td>row 1, cell 2</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> <td>row 1, cell 2</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> <td>row 1, cell 2</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> <td>row 1, cell 2</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> <td>row 1, cell 2</td> <td>row 1, cell 2</td> </tr> </table> </div>
This code snippet places the table within a wrapper div with a scrollbar. By assigning position: sticky to the th elements within the table header, the headers remain fixed as the content scrolls vertically.
The above is the detailed content of How can I create a scrollable table with fixed headers using only CSS?. For more information, please follow other related articles on the PHP Chinese website!