Home >Web Front-end >CSS Tutorial >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:
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!