Home >Web Front-end >CSS Tutorial >Can CSS Alone Create a Cross-Browser Compatible Scrollable Table with Fixed Headers?

Can CSS Alone Create a Cross-Browser Compatible Scrollable Table with Fixed Headers?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-06 13:39:17283browse

Can CSS Alone Create a Cross-Browser Compatible Scrollable Table with Fixed Headers?

CSS-Only Scrollable Table with Fixed Headers

Question:

Is there a CSS-only solution to create scrollable tables with fixed headers that is cross-browser compliant?

Requirements:

  • Maintain column alignment between header, footer, and content rows
  • Keep the header and footer fixed while the content scrolls vertically
  • No jQuery or JavaScript required
  • Use only table-related tags (table, thead, tbody, tr, th, td)

Solution using Position: Sticky:

Compatibility Note: Check support for position:sticky before using this solution.

position:sticky positions an element relative to the nearest scrolling ancestor or the viewport if there are no scrolling ancestors. This behavior aligns with the desired sticky header.

However, assigning position:sticky to

, , or tags encounters issues in various browsers. Instead, assign the sticky property to
cells within a wrapper element that defines the scroll overflow.

Code:

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

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

/* Styling */
table {
  border-collapse: collapse;
}

th {
  background-color: #1976D2;
  color: #fff;
}

th,
td {
  padding: 1em .5em;
}

table tr {
  color: #212121;
}

table tr:nth-child(odd) {
  background-color: #BBDEFB;
}
<div>
  <table border="0">
    <thead>
      <tr>
        <th scope="col">head1</th>
        <th scope="col">head2</th>
        <th scope="col">head3</th>
        <th scope="col">head4</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>row 1, cell 1</td>
        <td>row 1, cell 2</td>
        <td>row 1, cell 2</td>
        <td>row 1, cell 2</td>
      </tr>
      <!-- additional rows omitted for brevity -->
    </tbody>
  </table>
</div>

The above is the detailed content of Can CSS Alone Create a Cross-Browser Compatible Scrollable Table with Fixed Headers?. 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