With large HTML tables, it becomes difficult to quickly reference rows and columns due to page scrolling. It would be beneficial to have the column headers fixed at the top of the table, similar to the "freeze panes" feature in Microsoft Excel.
For modern browsers, CSS transforms offer a straightforward solution. Without altering the existing HTML or CSS, you can implement fixed headers with just four lines of code:
document.getElementById("wrap").addEventListener("scroll", function() { var translate = "translate(0," + this.scrollTop + "px)"; this.querySelector("thead").style.transform = translate; });
This code attaches a scroll event listener to the container element ("wrap" in this example) and dynamically updates the CSS transform of the table head ("thead") to match the vertical scroll position of the table. This ensures that the headers remain fixed at the top of the table while allowing the body to scroll below.
Below is a complete example demonstrating this technique:
<div>
The above is the detailed content of How to Create Fixed Headers in HTML Tables Using CSS Transforms?. For more information, please follow other related articles on the PHP Chinese website!