In Microsoft Excel, we often use the "freeze panes" feature to keep the column headers stable while we scroll through the table contents. Is there a similar cross-browser technique in HTML?
Using CSS transforms, this can be done with just four lines of JavaScript code:
This approach has the following advantages:
Here is the code:
document.getElementById("wrap").addEventListener("scroll", function(){ var translate = "translate(0,"+this.scrollTop+"px)"; this.querySelector("thead").style.transform = translate; });
Below is a complete example for reference:
// JavaScript document.getElementById("wrap").addEventListener("scroll",function(){ var translate = "translate(0,"+this.scrollTop+"px)"; this.querySelector("thead").style.transform = translate; }); // CSS #wrap { overflow: auto; height: 400px; } td { background-color: green; width: 200px; height: 100px; } // HTML <div>
The above is the detailed content of How to Keep Table Headers Fixed While Scrolling the Body in HTML Using CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!