CSS-Only Solution for Fixed Headers
Problem:
Create a scrollable table with fixed headers and footers using only CSS and valid table tags, without requiring JavaScript or jQuery. Ensure that column alignment remains consistent between header, footer, and content rows.
Solution:
Using position: sticky
Wrap the table in a div: This will define the scroll area.
div { display: inline-block; height: 150px; overflow: auto; }
Apply position: sticky to table headers:
table th { position: -webkit-sticky; position: sticky; top: 0; }
Styling
Customize the table appearance as needed:
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; }
Example:
<div> <table border="0"> <thead> <tr> <th scope="col">head1</th> <th scope="col">head2</th> <th scope="col">head3</th> <th scope="col">head4</th> </tr> </thead> <tbody> <!-- Insert rows here --> </tbody> </table> </div>
Note:
The above is the detailed content of How to Create a Scrollable Table with Fixed Headers Using Only CSS?. For more information, please follow other related articles on the PHP Chinese website!