Home >Web Front-end >JS Tutorial >How to Create Fixed Headers in HTML Tables Using CSS Transforms?

How to Create Fixed Headers in HTML Tables Using CSS Transforms?

Barbara Streisand
Barbara StreisandOriginal
2024-12-13 13:35:11898browse

How to Create Fixed Headers in HTML Tables Using CSS Transforms?

HTML Table with Fixed Headers?

With large HTML tables, it becomes difficult to quickly reference rows and columns due to page scrolling. It would be beneficial to have the column headers fixed at the top of the table, similar to the "freeze panes" feature in Microsoft Excel.

CSS Transforms for Modern Browsers

For modern browsers, CSS transforms offer a straightforward solution. Without altering the existing HTML or CSS, you can implement fixed headers with just four lines of code:

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

This code attaches a scroll event listener to the container element ("wrap" in this example) and dynamically updates the CSS transform of the table head ("thead") to match the vertical scroll position of the table. This ensures that the headers remain fixed at the top of the table while allowing the body to scroll below.

Full Example

Below is a complete example demonstrating this technique:

<div>

The above is the detailed content of How to Create Fixed Headers in HTML Tables 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