HTML tables are a great way to display tabular data. However, when tables are long, it can be difficult to keep track of the column headers. This is especially true if the table is wide and the headers are not visible on the screen.
One way to address this problem is to freeze the column headers so that they stay visible even when the table is scrolled. This can be achieved using a variety of CSS and JavaScript techniques.
If you only care about modern browsers, a fixed header can be achieved much easier by using CSS transforms. Here's how it works:
Here's the JavaScript code for this technique:
document.getElementById("wrap").addEventListener("scroll", function() { var translate = "translate(0," + this.scrollTop + "px)"; this.querySelector("thead").style.transform = translate; });
Here's a full example for reference:
<div>
#wrap { width: 100%; height: 400px; overflow: auto; } th { width: 200px; } td { width: 200px; height: 100px; background-color: lightgray; }
The above is the detailed content of How Can I Keep HTML Table Headers Fixed While Scrolling?. For more information, please follow other related articles on the PHP Chinese website!