Home > Web Front-end > CSS Tutorial > How to Create a Fixed Header and Column in a Table Using Only CSS?

How to Create a Fixed Header and Column in a Table Using Only CSS?

Susan Sarandon
Release: 2024-12-08 09:08:11
Original
988 people have browsed it

How to Create a Fixed Header and Column in a Table Using Only CSS?

Fixed Header and Column in a Table Using Pure CSS

Creating a table with a fixed header and a fixed first column using pure CSS can be achieved using the position: sticky property. This approach is more efficient and cross-browser compatible than solutions relying on JavaScript or jQuery.

Solution:

  1. Wrap the table in a container:

    `

    `

  2. Enable scrolling on the container:

    `div.container {
    overflow: scroll;
    }`

  3. Sticky the table header:

    `thead th {
    position: -webkit-sticky; / for Safari /
    position: sticky;
    top: 0;
    }`

  4. Sticky the first column:

    `tbody th {
    position: -webkit-sticky; / for Safari /
    position: sticky;
    left: 0;
    }`

  5. Optional: Sticky the header of the first column to the top left:

    `thead th:first-child {
    left: 0;
    z-index: 2;
    }`

Additional Notes:

  • For optimal performance, the container should have a maximum width and height set.
  • If the first column contains elements instead of , use tbody td:first-child in CSS instead of tbody th.
  • To style the header and first column further, adjust the CSS properties as needed.

Example:

<div class="container">
  <table border="1">
    <thead>
      <tr>
        <th>#</th>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th>1</th>
        <td>John Doe</td>
        <td>john@example.com</td>
        <td>(555) 123-4567</td>
      </tr>
      <tr>
        <th>2</th>
        <td>Jane Smith</td>
        <td>jane@example.com</td>
        <td>(555) 234-5678</td>
      </tr>
      <!-- More rows... -->
    </tbody>
  </table>
</div>
Copy after login
div.container {
  max-width: 500px;
  max-height: 300px;
  overflow: scroll;
}

thead th {
  position: sticky;
  top: 0;
}

tbody th {
  position: sticky;
  left: 0;
}

thead th:first-child {
  left: 0;
  z-index: 2;
}
Copy after login

The above is the detailed content of How to Create a Fixed Header and Column in a Table Using Only 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template