Home > Web Front-end > JS Tutorial > How Can I Freeze HTML Table Headers Using CSS and JavaScript?

How Can I Freeze HTML Table Headers Using CSS and JavaScript?

Barbara Streisand
Release: 2024-12-09 00:06:13
Original
364 people have browsed it

How Can I Freeze HTML Table Headers Using CSS and JavaScript?

CSS and JavaScript Techniques for Fixed HTML Table Headers

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.

CSS Transform Technique

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.

Advantages of CSS Transform Technique:

  • Minimal code (four lines)
  • No external dependencies
  • Works with various table configurations (table-layout)
  • Supports all major browsers except Internet Explorer 8-

Example Implementation:


   var translate = "translate(0," this.scrollTop "px)";<br>   this.querySelector("thead").style.transform = translate;<br>});

 Your existing container </em>/</p><h1>wrap {</h1><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">overflow: auto;
height: 400px;
Copy after login

}

/ CSS for demo /
td {

background-color: green;
width: 200px;
height: 100px;
Copy after login

}

<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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template