Home > Web Front-end > CSS Tutorial > How to Create a Scrollable HTML Table with Fixed Headers?

How to Create a Scrollable HTML Table with Fixed Headers?

Patricia Arquette
Release: 2024-12-08 03:03:10
Original
770 people have browsed it

How to Create a Scrollable HTML Table with Fixed Headers?

How to Anchor Headers in a Scrollable HTML Table

Incorporating both fixed table headers and scrollable table bodies can be a common requirement in web applications. However, finding an effective solution can be challenging. This guide will explore the solution to this issue, guiding you through the implementation.

The Solution

To achieve this functionality, you can utilize a combination of CSS and JavaScript techniques. A popular solution is to employ a technique known as double-scrolling. This involves creating two nested tables: an outer table containing the fixed header and a scrollable inner table for the table body.

CSS Setup

First, define the CSS styling for the tables:

/* Outer table (fixed header) */
#outer-table {
  width: 100%;
  height: 100px; /* Set a fixed height for the header */
  overflow: hidden;
}

/* Inner table (scrollable body) */
#inner-table {
  height: calc(100% - 100px); /* Calculate the height based on the outer table's height */
  overflow-y: scroll;
}
Copy after login

JavaScript Setup

Next, use JavaScript to adjust the inner table's height dynamically:

const outerTable = document.getElementById('outer-table');
const innerTable = document.getElementById('inner-table');

// Calculate the inner table's height based on the outer table's height
innerTable.style.height = `${outerTable.clientHeight - 100}px`;
Copy after login

Example

For a working example, refer to the following code sample:

<table>
Copy after login

This solution effectively freezes the table header while allowing the table body to scroll smoothly. By implementing these techniques, you can create responsive and interactive tables that meet your specific requirements.

The above is the detailed content of How to Create a Scrollable HTML Table with Fixed Headers?. 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