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
Release: 2024-12-24 02:36:17
Original
411 people have browsed it

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;
});
Copy after login
Copy after login

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;
});
Copy after login
Copy after login
#wrap {
  overflow: auto;
  height: 400px;
}

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

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!

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