Home > Article > Web Front-end > How to Make a Scrollable Table with Fixed Headers Using CSS?
Enhancing tables with fixed headers while maintaining a scrollable body is a common requirement in web development. This article will delve into a comprehensive solution using CSS.
In the provided scenario, a table within a scrollable container struggles to retain its header when scrolling. The underlying issue stems from the header and body being inextricably linked, causing them to scroll together.
The key to resolving this issue lies in separating the table's header () from its body (
). By setting display: block for both elements, we break their intrinsic connection, allowing them to function independently.To introduce scrolling capabilities to the body, assign overflow: auto and specify a desired height. Additionally, to prevent the header from drifting during scrolling, fix its width using CSS.
table tbody, table thead { display: block; } table tbody { overflow: auto; height: 100px; } th { width: 72px; } td { width: 72px; }
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; } table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; } /* ... and so on for each subsequent column */
By separating the table's header and body and implementing the aforementioned CSS properties, we successfully create a scrollable table with fixed headers, meeting the requirements of the original query.
The above is the detailed content of How to Make a Scrollable Table with Fixed Headers Using CSS?. For more information, please follow other related articles on the PHP Chinese website!