How can I create a table with minimal JavaScript using modern CSS?
I am aiming to include the following features:
- Fixed column(s) (positioning and width)
- Scrollable in both X and Y axes
- Responsive in the X axis (for non-fixed width columns).
https://i.sstatic.net/tVi2v.gif
Note: I have reviewed popular questions and answers on Stack Overflow, such as here and here, for example.
While solutions involving JavaScript event handlers for scroll events exist, where a fixed column moves along with the main column, I wonder if there are newer, more efficient ways given the advancements in CSS.
Is there a 2017/2018 solution that relies only on CSS or has minimal JS overhead?
I hope to avoid implementing JavaScript solutions that may break easily.
My ideas include:
a)
: Using position: fixed;
for fixed columns
Challenges:
- The height of
<td>
elements must be defined or calculated with JavaScript - A scroll event listener is required to programmatically scroll the fixed column
b)
: Utilizing div(s) to represent a "fake" left column while keeping the content inside the table scrollable
Challenges:
- Synchronizing div height with table row height
- Losing HTML semantic structure as the fixed "fake" column deviates from traditional table syntax
c)
: Creating multiple tables where each shows a portion of the data to maintain HTML markup integrity and fixed header/columns.
Challenges:
- Duplicating HTML X N times
- Requiring JavaScript to sync sizes and manage scrolling
An approach involving a scroll event listener and a fixed left column utilizing JavaScript could look like this:
// JavaScript code here
const firstColumn = [...document.querySelectorAll('table tr > *:first-of-type')];
const tableContainer = document.querySelector('.table-container');
tableContainer.addEventListener('scroll', function() {
const currentScrollPosition = this.scrollTop * -1;
firstColumn.forEach(el => el.style.marginTop = currentScrollPosition + 'px');
});
But is it possible to achieve this without relying on JavaScript?
About the suggestion of a possible duplicate:
The suggested possible duplicate mentioned in my question does not cover what I am seeking. While that question focuses on freezing a single left column, mine has a broader scope encompassing fixed headers, columns, and scrollable bodies.
The other question and its accepted answer date back to 2009! Given the specific focus and examples provided in my post, I believe revisiting this topic with modern CSS techniques is warranted. Additionally, the "JS solution" mentioned is merely an illustration of potential pitfalls, as I am specifically interested in contemporary CSS approaches for achieving these functionalities.