Home > Article > Web Front-end > How to Create Fixed Table Headers with CSS?
Fixing Table Headers with CSS
Creating a table with fixed headers can enhance readability and navigation, especially when dealing with large datasets. Let's explore how to achieve this using CSS:
Define Table Structure
The table should include both a header and a body, represented by and
elements respectively. Each row should be within aSeparate Header and Body
To separate the content of the header from the body, use display: block for both thead and tbody. This detaches them from the default table layout.
Apply Scrolling to the Body
Set overflow: auto on tbody to enable horizontal scrolling, and apply a height to limit the scrollable area.
Set Widths and Alignment
Set static widths for both th and td to align columns. Ensure that the header and body have the same total width.
Additional CSS
For more control over column widths, use nth-child selectors with min-width and max-width properties. This allows for varying column sizes while maintaining alignment.
Example Code
Here's a code snippet that demonstrates a table with fixed headers:
table { width: 100%; } table tbody, table thead { display: block; } table tbody { overflow: auto; height: 100px; } th, td { width: 100px; }
The above is the detailed content of How to Create Fixed Table Headers with CSS?. For more information, please follow other related articles on the PHP Chinese website!