We’ve covered that individual <table>
cells, <th>
and <td>
can be position: sticky
. It’s pretty easy to make the header of a table stick to the top of the screen while scrolling through a bunch or rows (like this demo).
But stickiness isn’t just for the top of the screen, you can stick things in any scroll direction (horizontal is just as fun). In fact, we can have multiple sticky elements stuck in different directions inside the same element, and even single elements that are stuck in multiple directions.
Here’s a video example of a table that sticks both the header and first column:
Why would you do that? Specifically for tabular data where cross-referencing is the point. In this table (which represents, of course, the scoring baseball game where somehow 20 teams are all playing each other at once because that’s how baseball works), it “makes sense” that you wouldn’t want the team name or the inning number to scroll away, as you’d lose context of what you’re looking at.
Not all tables need to be bi-directionally cross-referenceable. A lot of tables can smash rows into blocks on small screens for a better small-screen experience.
The “trick” at play here is partially the position: sticky;
usage, but moreso to me, how you have to handle overlapping elements. A table cell that is sticky needs to have a background, because otherwise we’ll see overlapping content. It also needs proper z-index
handling so that when it sticks in place, it’ll be on top of what it is supposed to be on top of. This feels like the trickiest part:
- Make sure the
tbody>th
cells are above regular table cells, so they stay on top during a horizontal scroll. - Make sure the
thead>th
cells are above those, for vertical scrolling. - Make sure the
thead>th:first-child
cell is the very highest, as it needs to be above the body cells and it’s sibling headers again for horizontal scrolling.
A bit of a dance, but it’s doable.
High five to Cameron Clark who emailed me demoed this and showed me how cool it is. And indeed, Cameron, it is cool. When I shared that around, Estelle Weyl showed me a demo she made several years ago. That feels about right, Estelle is always a couple of years ahead of me.
The post A table with both a sticky header and a sticky first column appeared first on CSS-Tricks.
You can support CSS-Tricks by being an MVP Supporter.
from CSS-Tricks https://ift.tt/3p1BT3n
via IFTTT
No comments:
Post a Comment