Home >Web Front-end >JS Tutorial >How Can I Freeze HTML Table Headers Using CSS and JavaScript?
The ability to freeze column headings in an HTML table, as seen in Microsoft Excel's "freeze panes" feature, is highly desirable for extended tables. There are several cross-browser techniques that can achieve this effect using either CSS or JavaScript.
For modern browsers, CSS transforms offer a simple and effective solution:
var translate = "translate(0," this.scrollTop "px)";<br> this.querySelector("thead").style.transform = translate;<br>});<br>
This code listens for scroll events on the table container and translates the table header (thead) based on the scroll position.
var translate = "translate(0," this.scrollTop "px)";<br> this.querySelector("thead").style.transform = translate;<br>});
Your existing container </em>/</p><h1>wrap {</h1><pre class="brush:php;toolbar:false">overflow: auto; height: 400px;
}
/ CSS for demo /
td {
background-color: green; width: 200px; height: 100px;
}
<pre class="brush:php;toolbar:false"><table> <thead> <tr> <th>Foo</th> <th>Bar</th> </tr> </thead> <tbody> <tr><td></td><td></td></tr> <tr><td></td><td></td></tr> <tr><td></td><td></td></tr> <tr><td></td><td></td></tr> <tr><td></td><td></td></tr> <tr><td></td><td></td></tr> <tr><td></td><td></td></tr> <tr><td></td><td></td></tr> <tr><td></td><td></td></tr> <tr><td></td><td></td></tr> <tr><td></td><td></td></tr> <tr><td></td><td></td></tr> </tbody> </table></p> <p></div>
The above is the detailed content of How Can I Freeze HTML Table Headers Using CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!