Home >Web Front-end >CSS Tutorial >How to Create a CSS-Only Scrollable Table with Fixed Headers?

How to Create a CSS-Only Scrollable Table with Fixed Headers?

Linda Hamilton
Linda HamiltonOriginal
2024-12-02 16:03:11398browse

How to Create a CSS-Only Scrollable Table with Fixed Headers?

CSS-Only Scrollable Table with Fixed Headers

In this question, the user seeks to create scrollable tables with fixed headers and footers using CSS only. Their specific requirements include:

  • Preserving column alignment between header, footer, and content rows
  • Keeping the header and footer fixed while allowing the content to scroll vertically
  • Accomplishing this solely with HTML table tags and CSS rules
  • Ensuring cross-browser compatibility

Answer

One possible solution is to utilize the position: sticky property. According to W3C, position: sticky defines an element's position in relation to its ancestor with a scrolling box or the viewport if no ancestor scrolls.

However, certain browsers (e.g., Chrome, IE, Edge) have encountered issues when assigning position: sticky to table header rows ( or ). An alternative approach that seems to work for tables is to assign it to table cells ().

To achieve the desired effect, the user can consider the following code:

div {
  display: inline-block;
  height: 150px;
  overflow: auto
}

table th {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
}

This code wraps the table in a div with overflow: auto to establish a scrollable area. The table headers are assigned a sticky position, ensuring they remain fixed as the content scrolls vertically.

Additional Styling for Aesthetics

The snippet includes additional CSS styling to enhance the table's appearance, but these aesthetics are not essential for the primary functionality of a scrollable table with fixed headers.

The above is the detailed content of How to Create a CSS-Only Scrollable Table with Fixed Headers?. 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