Border Style Does Not Work with Sticky Position Elements
Sticky positioning is a handy CSS property that allows elements to stay fixed in place on the screen, even when the user scrolls down the page. However, there can be complications when you try to apply border styles to sticky elements.
The Issue:
In the example provided, a table header is set to be sticky, and inline border styles have been applied to the
The Cause:
The conflict arises due to the use of border-collapse: collapse. With this property, the borders of adjacent table cells collapse and merge together. When combined with a sticky header, the merged borders are lost upon scrolling.
The Solution:
To overcome this issue, you can use border-collapse: separate, which prevents the collapse of borders. Additionally, you should tailor your borders to sit on specific sides of the cells and headers. This ensures that the borders remain attached and visible even when scrolling.
CSS Solution:
#wrapper { width: 100%; height: 150px; overflow: auto; } table { width: 100%; text-align: center; border-collapse: separate; /* Don't collapse */ border-spacing: 0; } table th { /* Apply both top and bottom borders to the <th> */ border-top: 2px solid; border-bottom: 2px solid; border-right: 2px solid; } table td { /* For cells, apply the border to one of each side only (right but not left, bottom but not top) */ border-bottom: 2px solid; border-right: 2px solid; } table th:first-child, table td:first-child { /* Apply a left border on the first <td> or <th> in a row */ border-left: 2px solid; } table thead th { position: sticky; top: 0; background-color: #edecec; }
By applying these styles, the border styles will remain visible even when the table is scrolled, preserving the desired design of the sticky header.
The above is the detailed content of Why Don\'t Border Styles Work on Sticky Positioned Table Headers, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!