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

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

Linda Hamilton
Release: 2024-12-02 22:34:11
Original
657 people have browsed it

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

CSS-Only Scrollable Table with Fixed Headers

Challenge:

The objective is to create a scrollable table with fixed headers using only CSS, ensuring cross-browser compatibility and meeting the following criteria:

  • Maintain column alignment between header, footer, and content rows
  • Keep header and footer fixed while the content scrolls vertically
  • Avoid reliance on JavaScript or jQuery
  • Utilize only the provided table tags (table, colgroup, col, thead, tbody, tfoot, tr, th, td)

Solution Using Position: Sticky:

Support for position: sticky should be checked prior to implementing this solution. As per the W3C, a sticky-positioned box is situated in a similar manner to a relatively positioned box. However, the offset is calculated relative to the closest ancestor with a scrolling box or the viewport if no ancestor has a scrolling box.

This behavior aligns with that of a static header. Assign the sticky position property to table-cell elements (th). Since a table is not a block-element that respects its assigned size, a wrapper element is used to define the scroll-overflow.

Example:

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

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

The above is the detailed content of How Can I Create a CSS-Only Scrollable Table with Fixed Headers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template