Home > Web Front-end > JS Tutorial > How Can I Keep HTML Table Headers Fixed While Scrolling?

How Can I Keep HTML Table Headers Fixed While Scrolling?

Patricia Arquette
Release: 2024-12-08 10:23:12
Original
738 people have browsed it

How Can I Keep HTML Table Headers Fixed While Scrolling?

Can You Keep HTML Table Headers Fixed When You Scroll?

HTML tables are a great way to display tabular data. However, when tables are long, it can be difficult to keep track of the column headers. This is especially true if the table is wide and the headers are not visible on the screen.

One way to address this problem is to freeze the column headers so that they stay visible even when the table is scrolled. This can be achieved using a variety of CSS and JavaScript techniques.

CSS Transforms

If you only care about modern browsers, a fixed header can be achieved much easier by using CSS transforms. Here's how it works:

  1. Add an event listener to the table wrapper. This listener will be triggered when the table is scrolled.
  2. Get the scrollTop value of the wrapper. This value represents the number of pixels the table has been scrolled vertically.
  3. Apply a translate transformation to the table header. This transformation will move the header up by the same number of pixels that the table has been scrolled.

Here's the JavaScript code for this technique:

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

Here's a full example for reference:

<div>
Copy after login
#wrap {
    width: 100%;
    height: 400px;
    overflow: auto;
}

th {
    width: 200px;
}

td {
    width: 200px;
    height: 100px;
    background-color: lightgray;
}
Copy after login

The above is the detailed content of How Can I Keep HTML Table Headers Fixed While Scrolling?. 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