In cases where a large table extends beyond the visible browser window, it's often desirable to have scrollbars on both the top and bottom to navigate the entire table content efficiently.
In pure HTML and CSS, this can be achieved by simulating a second horizontal scrollbar at the top. Here's how:
Create a Dummy Div:
Add a div element above the table and style it with a height sufficient to create the appearance of a scrollbar (e.g., 20px).
Disable Vertical Scrolling:
Set overflow-y: hidden for both the dummy div and the table's parent div to restrict scrolling to the horizontal axis.
Enable Horizontal Scrolling:
Set overflow-x: scroll for the dummy div and the table's parent div to enable horizontal scrolling in both areas.
Synchronize Scrollbars:
Utilize JavaScript to synchronize the scrolling of the dummy div and the table by attaching event listeners to the scroll event. When one scrollbar is moved, the other one adjusts accordingly.
Here's an example that puts a dummy div on top of the table's parent div:
HTML:
<div class="table-wrapper"> <div class="dummy-scrollbar"></div> <div class="data-table">
CSS:
.table-wrapper { height: 130%; overflow: auto; width: 100%; } .dummy-scrollbar { height: 20px; width: 100%; overflow-x: scroll; overflow-y: hidden; } .data-table { overflow-x: scroll; overflow-y: visible; width: 100%; }
JavaScript:
$(".table-wrapper").scroll(function() { $(".dummy-scrollbar").scrollLeft($(this).scrollLeft()); }); $(".dummy-scrollbar").scroll(function() { $(".table-wrapper").scrollLeft($(this).scrollLeft()); });
By implementing this approach, you can create the illusion of a second horizontal scrollbar on top of your table, enhancing navigation and accessibility.
The above is the detailed content of How to Create Dual Horizontal Scrollbars (Top and Bottom) for a Table using HTML, CSS, and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!