Home  >  Article  >  Web Front-end  >  How to Create Scrollable Tables with Fixed Headers Using CSS?

How to Create Scrollable Tables with Fixed Headers Using CSS?

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 09:42:01489browse

How to Create Scrollable Tables with Fixed Headers Using CSS?

How to Make Scrollable Tables with CSS and Fixed Headers

In web development, it's often necessary to create tables with large amounts of data that require scrolling. However, maintaining a fixed header while scrolling the table body can be challenging. Here's how you can achieve this effect:

HTML Structure

First, we must ensure our HTML structure is correct. We have an outer div with a scrollbar, an inner div containing the table, and the table headers should be within a element and table data within a element.

<div>

CSS Styles

Now, we need to style the table using CSS:

/* Separate header from body and allow both to scroll independently */
table tbody, table thead {
  display: block;
}

/* Enable scrolling for the table body */
table tbody {
  overflow: auto;
  height: 100px;
}

/* Fix the width of the header */
th {
  width: 72px;
}

/* Fix the width of the data cells */
td {
  width: 72px;
}

Additional Considerations

Ensure that all header and data cells are included in elements for proper alignment. If you want varying column widths, use the nth-child selector in CSS.

Note: This approach is suitable for smaller tables. For very large tables, consider using a different technique, such as virtualization or a third-party library.

The above is the detailed content of How to Create Scrollable Tables 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