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

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

DDD
Release: 2024-11-23 00:48:11
Original
816 people have browsed it

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

Creating a Scrollable Table with Fixed Headers Using CSS

When creating tables that require scrolling due to excessive data, it can be useful to have the table header fixed while the data rows scroll independently. This article will provide a detailed solution to achieve this using CSS.

Solution

To create a scrollable table with fixed headers, it is essential to separate the header elements from the data rows using the and tags. CSS styling can then be applied to control their display and scrolling behavior.

CSS Styles:

table tbody, table thead {
  display: block;
}

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

th {
  width: 72px;
}

td {
  width: 72px;
}
Copy after login

The display: block property on and separates the header and body elements, allowing them to behave independently. overflow: auto and height on enable scrolling for the data rows. Static widths are set for both and to ensure alignment.

Note: Ensure that the tag is used for both the header and data rows.

Enhanced Control over Column Widths:

For tables with varying column widths, use CSS to specify minimum and maximum widths:

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; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
Copy after login

This technique provides granular control over column widths while maintaining the alignment between the header and data rows.

The above is the detailed content of How to Create a Scrollable Table with Fixed Headers Using CSS?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template