Home  >  Article  >  Web Front-end  >  How to Make a Scrollable Table with Fixed Headers Using CSS?

How to Make a Scrollable Table with Fixed Headers Using CSS?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 01:18:02145browse

How to Make a Scrollable Table with Fixed Headers Using CSS?

How to Craft Scrollable Tables with Fixed Headers in 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.

The Problem

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 Solution

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.

Code Snippet

table tbody, table thead {
    display: block;
}

table tbody {
    overflow: auto;
    height: 100px;
}

th {
    width: 72px;
}

td {
    width: 72px;
}

Additional Considerations

  • Missing HTML Elements: Ensure all rows are enclosed within elements, including the header row.
  • Column Width Control: For nuanced control over column widths while maintaining alignment, consider using the following code:
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 */

Conclusion

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn