Ways to address a header in a table while scrolling

My table's thead section contains 2 tr elements with different colspans and rowspans, as shown in the image below:

https://i.sstatic.net/5aLJO.png

<table id="header-fixed">
    <thead>                     
        <tr id="tr1" role="row" style="background-color: rgb(204, 9, 47);">
            <th rowspan="2" colspan="1">Unit</th>
            <th rowspan="1" colspan="1">Budgeted</th>
            <th rowspan="1" colspan="1">Accomplished</th>
            <th rowspan="1" colspan="3">Result Attainment - Variation</th>
        </tr>
        <tr id="tr2" role="row" style="background-color: rgb(204, 9, 47);">
            <th rowspan="1" colspan="1">Result</th>
            <th rowspan="1" colspan="1">Result</th>
            <th rowspan="1" colspan="1">Variation</th>
            <th rowspan="1" colspan="1">%</th>
            <th rowspan="1" colspan="1">Attained</th>
        </tr>
    </thead>
...
</table>

I am trying to make the header of this table fixed when scrolling, and I came across this code:

While this code almost works and fixes the header on scroll, the column widths are not aligned properly like in this image.

https://i.sstatic.net/A6NN6.png

Is there anyone who can assist me with this issue?

Answer №1

give this sample a try

    td {
      border-bottom: 1px solid #ccc;
      padding: 5px;
      text-align: left; /* IE */
    }
    td + td {
      border-left: 1px solid #ccc;
    }
    th {
      padding: 0 5px;
      text-align: left; /* IE */
    }
    .header-background {
      border-bottom: 1px solid black;
    }
    
    /* the above styles are for decoration purposes only, not part of the test */
    
    .fixed-table-container {
      width: 50%;
      height: 200px;
      border: 1px solid black;
      margin: 10px auto;
      background-color: white;
      /* the above styles are either decorative or flexible */
      position: relative; /* could be absolute or relative */
      padding-top: 30px; /* height of header */
    }

    .fixed-table-container-inner {
      overflow-x: hidden;
      overflow-y: auto;
      height: 100%;
    }
     
    .header-background {
      background-color: #D5ECFF;
      height: 30px; /* height of header */
      position: absolute;
      top: 0;
      right: 0;
      left: 0;
    }
    
    table {
      background-color: white;
      width: 100%;
      overflow-x: hidden;
      overflow-y: auto;
    }

    .th-inner {
      position: absolute;
      top: 0;
      line-height: 30px; /* height of header */
      text-align: left;
      border-left: 1px solid black;
      padding-left: 5px;
      margin-left: -5px;
    }
    .first .th-inner {
        border-left: none;
        padding-left: 6px;
      }


    
    /* handling complex headers */
    
    .complex.fixed-table-container {
      padding-top: 60px; /* height of header */
      overflow-x: hidden; /* for border */
    }
    
    .complex .header-background {
      height: 60px;
    }
    
    .complex-top .th-inner {
      border-bottom: 1px solid black;
      width: 100%
    }
    
    .complex-bottom .th-inner {
      top: 30px;
      width: 100%
    }
    
    .complex-top .third .th-inner { /* double row cell */
      height: 60px;
      border-bottom: none;
      background-color: #D5ECFF;
    }
    
 <div class="fixed-table-container complex">
      <div class="header-background"> </div>
      <div class="fixed-table-container-inner">
        <table cellspacing="0">
          <thead>
            <tr class="complex-top">
              <th class="first" colspan="2">
                <div class="th-inner">First and Second</div>
              </th>
              <th class="third" rowspan="2">
                <div class="th-inner">Third</div>
              </th>
            </tr>
            <tr class="complex-bottom">
              <th class="first">
                <div class="th-inner">First</div>
              </th>
              <th class="second">
                <div class="th-inner">Second</div>
              </th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>First</td>
              <td>First</td>
              <td>First</td>
            </tr>
            <tr>
              <td>First</td>
              <td>Second</td>
              <td>Third</td>
            </tr>
            <tr>
              <td>First</td>
              <td>Second</td>
              <td>Third</td>
            </tr>
            
            <!-- Additional table rows omitted for brevity -->
          
            <tr>
              <td>Last</td>
              <td>Last</td>
              <td>Last</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

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

JavaScript - Sending Form Data with Local Time

I want to automatically submit a form at a specific time of day The form should be submitted every day at "15:30:00" Here is the JavaScript code I have written: <script type="text/javascript> function initClock() { var now = new Date(); var h ...

Sharing on Facebook and prerendering in an angularjs application

Recently, I implemented prerender.io middleware on my Tomcat server, which is running Java webservices and an AngularJS app. The prerender service is functioning correctly, and I can see the pages being added to the list when I send a request simulating t ...

The Google Share button may fail to be displayed correctly if it was initially hidden

Is there a solution to the issue where the Google Share button does not display properly when it is initially hidden using CSS display:none on its parent div and then shown using jQuery .show()? I am currently experiencing this problem and I'm unsure ...

What is the best way to retrieve an item using a composite key?

const dynamoDB = new AWS.DynamoDB.DocumentClient(); var parameters: any = {}; parameters.TableName = 'StockDailyCandles'; var primarykey = { 'symbol': 'AAPL', 'datetime': '640590008898' }; // sa ...

Click a button to spin images around

Is there a way to rotate an image by 90 degrees, 180 degrees, and 360 degrees with the click of a button? <img class="test" id="image" src="images/image" alt="This is the Display Image" /> I attempted to use the following script, but was not satisf ...

Leveraging bootstrap for achieving vertical and horizontal centering of images

My webpage uses bootstrap to display content, and while I've managed to center my images vertically, I'm facing an issue with horizontal centering. I want to ensure that any image, regardless of size, remains within the column/row and adjusts it ...

The hamburger menu on the navigation bar only functions the first time it is clicked

I've encountered an issue with my hidden menu nav bar. The hamburger and close buttons only work once. Should I organize the events within a function and call it at the end, or perhaps use a loop for the button events? It's worth noting that I d ...

RxJS emits an array of strings with a one second interval between each emission

Currently, my code is set up to transform an Observable<string[]> into an Observable<string>, emitting the values one second apart from each other. It's like a message ticker on a website. Here's how it works at the moment: const ...

Is it possible to incorporate a React app as a component within a static HTML page?

Looking to integrate the react-csv-viewer component into a static HTML page without deploying it on a local server. I've tried following the instructions from the React tutorial, but am struggling with the build process. My goal is simple - to use th ...

Using Javascript to display different div elements based on the type of mobile device

My goal is to use JavaScript to accomplish the following: 1- Check the mobile device type, if it is an ANDROID device, show the ANDROID_USERS div. If it is an IPHONE device, show the IOS_USERS div. 2- Display the above div only once during the first visit ...

What is the best way to incorporate a button that, when clicked, reveals two separate images on the frontend?

describe food option heredescribe juice option hereHow can I create a button using HTML, CSS, JavaScript, and Bootstrap that displays different images for food and juices when clicked? For example, clicking on "food" will display 3 different food images, w ...

What could be causing compatibility issues between jQuery and Bootstrap 4 alpha 6?

I am encountering issues while trying to utilize jQuery in my project. Despite rearranging the script tags, I haven't been able to resolve the errors. Below is a snippet of the code: <!DOCTYPE html> <html lang="en"> <head> < ...

The PHP DOM feature is inserting an additional <p> element along with <html> and <body> tags

When it comes to displaying different images for desktop and mobile users based on their device, I have implemented a function in my index.php file. The code snippet from my index.php file: <!DOCTYPE html> <html class="no-js" lang="en"> <h ...

Exploring Vue.js: Pre-viewing an Image Before Updating it

Hey there! I have a custom component where I am trying to display an image. I want to show a preview of the image after selecting it, but before uploading it to the server. Can someone please help me with this? I attempted to use the v-on:change event on ...

React code displaying misalignment between label and input

Can you help me align my URL and https:// on the same margin? https://i.sstatic.net/hxkkC.png <div className="card"> <div className="card-body"> <div className="form-group col-12"> <label cla ...

Undefined React custom hooks can be a tricky issue to troub

Just delving into the world of React and trying to wrap my head around custom hooks, but I keep hitting roadblocks. Here's the latest hurdle that I'm facing, hoping for some guidance. I'm taking a step-by-step approach to creating a functio ...

How to prevent VueJS observer from monitoring a temporary variable

My VueJS and Observer objects are causing me trouble. I am encountering an issue where I assign a part of my object to a temporary variable for later use, update the original part with new data, and then revert it back to its original state after 8 seconds ...

Tips for successfully executing child_process.exec within an ajax request

On a server that I have access to but not ownership of, there is a node js / express application running on port 3000. Various scripts are typically executed manually from the terminal or via cron job. My goal is to have a button on the client-side that tr ...

Changes in state cause React to unmount listed objects

In my React (TS) application, I have two components. App.tsx: import { useState } from 'react' import Number from './Number' import './App.css' function App() { const [list, setList] = useState(["1", "2", "3", "4"]); ...

Regular expressions can be used to extract specific attributes and inner content from a div element within a contentEditable container

Context I am currently developing a tagging system called @Name for my website. Successfully, I have managed to detect names upon keystroke and replace the content with the corresponding div class='tag' data-id='User-id'>Name</di ...