Fixed Header and Column in a Table Using Pure CSS
Creating a table with a fixed header and a fixed first column using pure CSS can be achieved using the position: sticky property. This approach is more efficient and cross-browser compatible than solutions relying on JavaScript or jQuery.
Solution:
Wrap the table in a container:
`
Enable scrolling on the container:
`div.container {
overflow: scroll;
}`
Sticky the table header:
`thead th {
position: -webkit-sticky; / for Safari /
position: sticky;
top: 0;
}`
Sticky the first column:
`tbody th {
position: -webkit-sticky; / for Safari /
position: sticky;
left: 0;
}`
Optional: Sticky the header of the first column to the top left:
`thead th:first-child {
left: 0;
z-index: 2;
}`
Additional Notes:
Example:
<div class="container"> <table border="1"> <thead> <tr> <th>#</th> <th>Name</th> <th>Email</th> <th>Phone</th> </tr> </thead> <tbody> <tr> <th>1</th> <td>John Doe</td> <td>john@example.com</td> <td>(555) 123-4567</td> </tr> <tr> <th>2</th> <td>Jane Smith</td> <td>jane@example.com</td> <td>(555) 234-5678</td> </tr> <!-- More rows... --> </tbody> </table> </div>
div.container { max-width: 500px; max-height: 300px; overflow: scroll; } thead th { position: sticky; top: 0; } tbody th { position: sticky; left: 0; } thead th:first-child { left: 0; z-index: 2; }
The above is the detailed content of How to Create a Fixed Header and Column in a Table Using Only CSS?. For more information, please follow other related articles on the PHP Chinese website!