Home > Web Front-end > CSS Tutorial > How to Create a Scrollable Table Body with a Fixed Header Using CSS?

How to Create a Scrollable Table Body with a Fixed Header Using CSS?

Barbara Streisand
Release: 2024-12-20 21:29:10
Original
1061 people have browsed it

How to Create a Scrollable Table Body with a Fixed Header Using CSS?

Create Scrollable Table Body with Fixed Header

When working with large tables, it often becomes necessary to fix the header while allowing the body to be scrollable. This way, users can easily navigate through the data without losing track of the column headings.

Using CSS Position: Sticky

For modern browsers like Chrome, Firefox, and Edge, a simple CSS solution can provide the desired behavior. By applying position: sticky; top: 0; to the th elements, you can make the header fixed at the top of the table, while allowing the tbody to scroll independently.

.tableFixHead {
  overflow: auto;
  height: 100px;
}

.tableFixHead thead th {
  position: sticky;
  top: 0;
  z-index: 1;
}
Copy after login

Additional CSS

To enhance the appearance and functionality of the table, include additional CSS as necessary. For example:

table {
  border-collapse: collapse;
  width: 100%;
}

th, td {
  padding: 8px 16px;
}

th {
  background: #eee;
}
Copy after login

HTML Structure

Within a div with the class "tableFixHead," add your table with thead and tbody elements.

<div>
Copy after login

The above is the detailed content of How to Create a Scrollable Table Body with a Fixed Header Using CSS?. For more information, please follow other related articles on the PHP Chinese website!

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