How do I create an HTML table with a fixed/frozen left column and a scrollable body?
To create a scrollable table with a fixed left column, use CSS's position: sticky
. Wrap your table in a div. This creates an area with overflow-x: auto
for horizontal scrolling. Apply position: sticky; left: 0;
to your first th
and td
elements to freeze the column. Check it out:
Set a background on sticky elements to keep them visible, even when there is scrolled content behind them. This snippet will give you a brief jump-start into the world of fixed-column, scrollable table design.
Get the best out of position: sticky
position: sticky
, the star of our design, combines the best of position: relative
and position: fixed
. In layman's terms, it's just like your pet that loyally follows around until it finds its favorite spot, then sticks there. Sounds ideal for a scrollable table, right?
Battle of widths
Always set a definite width for your sticky elements, or they might end up battling each other for space, often leading to unexpected shifts and Game of Widths
. Use min-width
and max-width
to defend against content of varying size, keeping your layout flexible and responsive.
Compatibility: the survival game
position: sticky
is widely supported, but like assuming everyone knows the difference between git pull
and git fetch
, we shouldn't assume everyone supports this property. Do a double-check with resources like caniuse.com. IE 11 and lower versions aren't fans of sticky positioning. Legacy browser support is a real survival game.
Fixin' up the style
It's not just about making the table functional, but also presentable. Be aware of handling the borders and padding of your sticky table elements. The CSS properties border-collapse: separate
and border-spacing: 0
will be your loyal subjects in handling the table cell borders. For styling harmony, consider using different table structures and opt for a dual table setup.
Backup plan: alternatives for older browsers
For those still living in the past (Internet Explorer, I'm looking at you), the position: sticky
won't work. In such cases, position: absolute
within a container on position: relative
can be a lifesaver, but it won't be smooth sailing. You'll probably need JavaScript to keep things under control and synchronize the scrolling.
Some handy plugins
Some tasks demand the use of a sledgehammer. Enter jQuery plugins such as fixedheadertable.com's plugin, which offer a quick and robust way to implement fixed columns and headers in tables. Remember, we are standing on the shoulders of giants.
Was this article helpful?