A modern CSS solution for a fixed columns and header layout in a scrollable table

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.

Answer №1

One possible solution is to utilize the relatively new position:sticky property for achieving this effect. This approach minimizes the need for excessive JavaScript coding.

div{
  overflow:auto;
  width:100%;
  height:200px;
}
td,
th {
  border: 1px solid #000;
  width: 100px;
}
th {background-color:red;}

table {
  table-layout: fixed;
  width:100%;
}
td:first-child, th:first-child {
  position:sticky;
  left:0;
  z-index:1;
  background-color:grey;
}
td:last-child, th:last-child {
  position:sticky;
  right:0;
  z-index:1;
  background-color:blue;
}
thead tr th {
  position:sticky;
  top:0;
}
th:first-child, th:last-child {z-index:2;background-color:red;}
<div>
  <table>
    <thead>
      <tr>
        <th>&nbsp;&nbsp;&nbsp;</th>
        <th>&nbsp;&nbsp;&nbsp;</th>
        <th>&nbsp;&nbsp;&nbsp;</th>
        <th>&nbsp;&nbsp;&nbsp;</th>
        <th>&nbsp;&nbsp;&nbsp;</th>
        <th>&nbsp;&nbsp;&nbsp;</th>
        <th>&nbsp;&nbsp;&nbsp;</th>
        <th>&nbsp;&nbsp;&nbsp;</th>
        <th>&nbsp;&nbsp;&nbsp;</th>
        <th>&nbsp;&nbsp;&nbsp;</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
        <td>&nbsp;&nbsp;&nbsp;</td>
      </tr>

      <!-- Additional rows with similar structure -->

    </tbody>
  </table>
</div>

Answer №2

Explore my code snippet featuring a fixed header and the first column adjustment.

    <style type="text/css">
    .table {
          font-family: arial, sans-serif;
  border-collapse: collapse;
}

.th {
  width: 126px;
  height: 56px;
  padding: 0px 16px;
  text-align: left;
  background-color: #fafafa;
}

.td {
  width: 118px;
  min-width: 118px;
  max-width: 118px;
  height: 56px;
  max-height: 56px;
  overflow: hidden;
  text-align: center;
  border-bottom: 2px solid #dddddd;
}
.pink_color {
  background-color: pink;
}

.table_wrapper {
  position: relative;
}
.table_scroll {
  height: 73vh;
  overflow: auto;
}
.table_wrapper table {
  width: 100%;
}

.table_wrapper table thead th .text {
  position: absolute;
  z-index: 2;
}
.tableFixHead
{ 
  overflow: auto; height: 63vh; 
}
.tableFixHead thead th 
{ 
  position: sticky; top: 0; z-index: 1; 
}


@media only screen and (min-width: 1440px) {
  .table_scroll {
    height: 77vh;
    overflow: auto;
  }
}
</style>

<div style="padding-top: 16px;">
    <div class="table_wrapper">
        <div class="tableFixHead">
            <table class="table">
                <thead>
                  <th style="position: sticky; left: 0; z-index: 3;" class="text th"></th>
                  <th class="text th">1</th>
                  <th class="text th">1</th>
                  <th class="text th">1</th>
                  <th class="text th">1</th>
                  <th class="text th">1</th>
                  <th class="text th">1</th>
                  <th class="text th">1</th>
                  <th class="text th">1</th>
                  <th class="text th">1</th>
                  <th class="text th">1</th>
                  <th class="text th">1</th>
                  <th class="text th">1</th>
                  <th class="text th">1</th>
                </thead>
                <tr>
                  <td style="position: sticky; left: 0; z-index: 2; background: #fafafa;" class="td">test</td>
                    <td class="td">test1</td>
                    <td class="td">test1</td>
                    <td class="td">test1</td>
                    <td class="td">test1</td>
...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide for positioning all navbar items except one to the left, beginning at the left edge, utilizing a set minimum and maximum width, while moving the final item to the right edge

Is there a way to align all items in a navbar except for one to the left, with a fixed combined minimum and maximum width of 300px-400px, while sending the last item to the right margin? I want the final result to resemble this: https://i.stack.imgur.com ...

Utilize mapping function to merge arrays

Currently facing an issue with no clear solution in sight. When making API calls via a map, I am able to successfully log all results individually. However, my challenge lies in combining these results into a single array. var alpha = ['a', &apo ...

Revamp the button's visual presentation when it is in an active state

Currently, I'm facing a challenge with altering the visual appearance of a button. Specifically, I want to make it resemble an arrow protruding from it, indicating that it is the active button. The button in question is enclosed within a card componen ...

Issue with .submit() not submitting form after setTimeout timer runs out

How can I add a delay after a user clicks submit on a form before it actually submits? I have an image that appears when the click event is triggered, but the form never actually submits... This is the HTML form in question: <form class='loginFor ...

When I attempted to run `npm start`, an error with status code 1 was thrown,

Upon running npm start, the following error is displayed: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d4c5d5d6d1d031c031d">[email protected]</a> start /Users/user/Desktop/react-tutorial > react-script ...

image in the background following the header

Live Example: http://jsbin.com/opokev/54 I am currently trying to set this image as the background image while also including a header, but as you can see in the demo, the header is overlapping the image. Is there a way I can rearrange this so that the h ...

Retrieve the value of the object within the mysterious index loop in JavaScript

I have retrieved search results from the data, and each time the index of my search result varies. At one point, the result may appear in the 4th index, while at another time it might be in the 100th index. How can I retrieve the rank value from within t ...

Leveraging JQuery to Invoke Partial View

I have a partial view in my /Shared folder that is defined as follows: <div id="myProducts"> @Html.Partial("_ProductsList",Model) </div> I am attempting to refresh the _ProductsList view using jQuery. Specifically, I wan ...

What could be the reason for the malfunction of jQuery's show() function?

Using jQuery, I have implemented a functionality to hide a div using the hide() method. However, upon clicking a link, the div is supposed to show but unexpectedly disappears after appearing briefly. HTML Code Snippet <div id="introContent"> & ...

Transfer a JSON object to a Java Class without relying on a servlet

I have a form in HTML where I collect user input and store it as an object in JavaScript. Here is how I am creating the object: var dataObject = { Name: getName(), Age : getAge() } Now, I want to send this object using Ajax to a b ...

Maximum opacity in Three.js fog

My Current Endeavor: I am in the process of developing a lightweight GIS application with topography. One feature I want to implement is atmosphere haze. The Code I'm Working With: (Please bear with me as I have multiple scenes) fogColor = new T ...

change the width of a div element to match that of its nearest sibling element

Can the width of a div be automatically set to match its closest sibling when the width is set to width: auto;? In my coding example on jsFiddle, you can observe three colored divs - red, green, and blue. I am aiming for the blue div to adjust its size ba ...

Adjust the height in proportion to the width

My goal is to adjust the height of the li's based on their width using JQuery. var width = $('li').width(); $('li').css('height', width + 'px'); However, I've encountered an issue as it doesn't resu ...

ERROR : The value was modified after it had already been checked for changes

Encountering an issue with [height] on the main component and seeking a solution Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '753'. Current value: '731'. I have th ...

Unlocking the Secret Code

Presenting the question: checkPassword([["Peter", "P"], ["Sarah", "S"], ["Ethan", "R"]], {"Peter": "P", "Sarah": "Q", //"Ethan":"E"}) ...

Achieving space between elements using Flexbox with a line separating each row

I have already found a solution to this question, but I am interested in exploring better alternatives. My goal is to utilize flexbox to create rows of items with equal spacing and dividing lines between them. The examples provided in the code snippet achi ...

My desire is for every circle to shift consecutively at various intervals using Javascript

I'm looking to draw circles in a sequential manner. I am trying to create an aimbooster game similar to . Instead of drawing all the circles at once, I want each circle to appear after a few seconds. The circles I've created currently do not g ...

Firestore Query sends data object to browser

When making a Firestore query, the browser is displaying [object Object],[object Object] instead of the expected output: router.get('/jobopportunities', async(req, res) => { var jobArray = []; const snapshot = await fireba ...

Activate the active class on the icon when hovering over a dynamically generated span using Vue

Is it possible to activate multiple music notes when hovering over one? For example, if I hover over music note 2, both note 1 and note 2 should get active classes. And if I hover over note 3, then all three spans/icons should become active. I have succes ...

What is the correct method for downloading an Excel file in a Vue.js application?

I am having difficulty downloading an Excel file in xlsx format using my Vue.js application. The Vue.js application sends a post request to the Node.js application which then downloads the Excel file from a remote SFTP server. The backend application is fu ...