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

How to Create Fixed Table Headers with CSS?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-13 14:02:02634browse

How to Create Fixed Table Headers with CSS?

Fixing Table Headers with CSS

Creating a table with fixed headers can enhance readability and navigation, especially when dealing with large datasets. Let's explore how to achieve this using CSS:

Define Table Structure

The table should include both a header and a body, represented by and elements respectively. Each row should be within a element, including the header row.

Separate Header and Body

To separate the content of the header from the body, use display: block for both thead and tbody. This detaches them from the default table layout.

Apply Scrolling to the Body

Set overflow: auto on tbody to enable horizontal scrolling, and apply a height to limit the scrollable area.

Set Widths and Alignment

Set static widths for both th and td to align columns. Ensure that the header and body have the same total width.

Additional CSS

For more control over column widths, use nth-child selectors with min-width and max-width properties. This allows for varying column sizes while maintaining alignment.

Example Code

Here's a code snippet that demonstrates a table with fixed headers:

table {
  width: 100%;
}

table tbody,
table thead {
  display: block;
}

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

th,
td {
  width: 100px;
}

The above is the detailed content of How to Create Fixed Table Headers with 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