How to Create a Fixed Header and Column in a Table Using Only CSS?
Dec 08, 2024 am 09:08 AMFixed 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:
-
Wrap the table in a container:
`<div>
</div>`
-
Enable scrolling on the container:
`div.container {
overflow: scroll;
}` -
Sticky the table header:
`thead th {
position: -webkit-sticky; / for Safari /
position: sticky;
top: 0;
}` -
Sticky the first column:
`tbody th {
position: -webkit-sticky; / for Safari /
position: sticky;
left: 0;
}` -
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 <td> elements instead of <th>, 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>
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; }
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Adding Box Shadows to WordPress Blocks and Elements

Create a JavaScript Contact Form With the Smart Forms Framework

Create an Inline Text Editor With the contentEditable Attribute

Making Your First Custom Svelte Transition

Comparing the 5 Best PHP Form Builders (And 3 Free Scripts)

File Upload With Multer in Node.js and Express

Best CSS Animations and Effects on CodeCanyon 2025 (Paid Free)
