Creating a Scrollable Table with Fixed Headers Using CSS
When creating tables that require scrolling due to excessive data, it can be useful to have the table header fixed while the data rows scroll independently. This article will provide a detailed solution to achieve this using CSS.
Solution
To create a scrollable table with fixed headers, it is essential to separate the header elements from the data rows using the and
tags. CSS styling can then be applied to control their display and scrolling behavior.CSS Styles:
table tbody, table thead { display: block; } table tbody { overflow: auto; height: 100px; } th { width: 72px; } td { width: 72px; }
The display: block property on and
separates the header and body elements, allowing them to behave independently. overflow: auto and height on enable scrolling for the data rows. Static widths are set for bothNote: Ensure that the
Enhanced Control over Column Widths:
For tables with varying column widths, use CSS to specify minimum and maximum widths:
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; } table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; } table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
This technique provides granular control over column widths while maintaining the alignment between the header and data rows.
The above is the detailed content of How to Create a Scrollable Table with Fixed Headers Using CSS?. For more information, please follow other related articles on the PHP Chinese website!