Home >Web Front-end >JS Tutorial >How to Create an HTML Table with Fixed Headers Using CSS Transforms?

How to Create an HTML Table with Fixed Headers Using CSS Transforms?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 02:36:17440browse

How to Create an HTML Table with Fixed Headers Using CSS Transforms?

HTML Table with Fixed Headers

Problem Statement

Create an HTML table where the column headers remain fixed on the screen as you scroll through the table's contents. This mimics the "freeze panes" feature in Microsoft Excel.

Modern Browsers Solution

Using CSS transforms, fixing the header is straightforward for modern browsers:

  1. Set the "transform" property for the table's "thead" element.
  2. Translate by the current scrollTop value.
  3. Listen to the "scroll" event on the containing element ("#wrap").
document.getElementById("wrap").addEventListener("scroll", function(){
  var translate = "translate(0," + this.scrollTop + "px)";
  this.querySelector("thead").style.transform = translate;
});

Support and Example

CSS transforms are widely supported, except for Internet Explorer 8-.

Here's the full example:

document.getElementById("wrap").addEventListener("scroll", function(){
  var translate = "translate(0," + this.scrollTop + "px)";
  this.querySelector("thead").style.transform = translate;
});
#wrap {
  overflow: auto;
  height: 400px;
}

td {
  background-color: green;
  width: 200px;
  height: 100px;
}
<div>

The above is the detailed content of How to Create an HTML Table with Fixed Headers Using CSS Transforms?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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