Home > Web Front-end > JS Tutorial > How to Keep Table Headers Fixed While Scrolling the Body in HTML Using CSS and JavaScript?

How to Keep Table Headers Fixed While Scrolling the Body in HTML Using CSS and JavaScript?

Barbara Streisand
Release: 2024-12-15 07:49:12
Original
411 people have browsed it

How to Keep Table Headers Fixed While Scrolling the Body in HTML Using CSS and JavaScript?

Is there a cross-browser CSS/JavaScript technique to display a long HTML table such that the column headers stay fixed on-screen and do not scroll with the table body?

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:

  1. Wrap your table in a container with the ID "wrap" and set its overflow property to "auto".
  2. Listen for the "scroll" event on the container.
  3. Inside the event handler, calculate the translation value based on the scrollTop property.
  4. Apply the calculated translation value to the table's thead element using the transform property.

This approach has the following advantages:

  • Clean and efficient, using only four lines of JavaScript.
  • No external JavaScript dependencies.
  • Works with all table configurations, including fixed layout.
  • Supports modern browsers, including Chrome, Safari, Firefox, and Edge.

Here is the code:

document.getElementById("wrap").addEventListener("scroll", function(){
   var translate = "translate(0,"+this.scrollTop+"px)";
   this.querySelector("thead").style.transform = translate;
});
Copy after login

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>
Copy after login

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!

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