Home >Web Front-end >CSS Tutorial >How to Create a Fixed Header Table with Both Horizontal and Vertical Scrollbars?

How to Create a Fixed Header Table with Both Horizontal and Vertical Scrollbars?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 09:06:09390browse

How to Create a Fixed Header Table with Both Horizontal and Vertical Scrollbars?

Fixed header table with horizontal scrollbar and vertical scrollbar on

Problem:

Creating a fixed header table with horizontal and vertical scrollbars can be challenging when both scrollbars are required. The issue arises when the outer container is positioned absolutely, which can cause the vertical scrollbar to interfere with the header, preventing it from being fixed in place.

HTML:

The HTML structure is relatively straightforward:

<div class="outer-container">
  <div class="inner-container">
    <div class="table-header">...</div>
    <div class="table-body">...</div>
  </div>
</div>

CSS:

The CSS styles position the outer container absolutely and handle the overflowing content:

.outer-container {
  position: absolute;
  overflow: hidden;
}

.inner-container {
  overflow-x: scroll;
}

.table-header {
  position: absolute;
  width: 100%;
}

.table-body {
  overflow-y: scroll;
  height: calc(100% - 40px); /* Adjust this value to match the height of the header */
}

Solution:

The key to fixing this issue is to handle the scrolling of the table header and body in synchronization. Here's a possible solution:

  1. Set the position of the .table-header to absolute. This will keep it positioned within the .inner-container.
  2. Add a scroll event listener to the .table-body.
  3. In the event handler, set the left offset of the .table-header to the negative of the .table-body's horizontal scroll position. This will move the header along with the body as it scrolls horizontally.

JavaScript/jQuery:

The following script can be used to implement the scrolling synchronization:

$(".table-body").scroll(function() {
  $(".table-header").offset({ left: -this.scrollLeft });
});

Explanation:

This script ensures that when a user scrolls the .table-body horizontally, the .table-header scrolls along with it, maintaining its fixed position.

Note:

Adjust the height property of the .table-body in the CSS to match the height of the .table-header. This will prevent the body from overflowing onto the header.

The above is the detailed content of How to Create a Fixed Header Table with Both Horizontal and Vertical Scrollbars?. 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