Tips for designing a table with a stationary first column in HTML/CSS

I am looking to design a table that can be horizontally scrolled with a dynamic number of columns. The goal is to keep the first column fixed/frozen while scrolling horizontally. I attempted to achieve this using the following CSS, which successfully keeps the first column fixed but causes the second and third columns to be hidden under it.

   
.mydiv {
  overflow-y: scroll;
}
.headcol {
  position:absolute;
  width: 100px;
  text-align:center;
  background-color: #4CAF50;
  color: white;
  font-family:arial;
  font-size:13px;
  padding-left:15px;
  padding-right:15px;
  padding-top:10px;
  padding-bottom:10px;
  border: 1px solid #c4c0c0;
}

.tablemy {
  border-collapse: collapse;
  border: 1px solid #c4c0c0;
}

.thmy {
  text-align:center;
  background-color: #4CAF50;
  color: white;
  font-family:arial;
  font-size:13px;
  padding-left:15px;
  padding-right:15px;
  padding-top:10px;
  padding-bottom:10px;
  border: 1px solid #c4c0c0;
}

.tdmy {
  white-space: nowrap;
  padding:8px; 
  border-left:1px solid #ccc; 
  border-top:1px solid #ccc;
  padding-left:15px;
  padding-right:15px;
  padding-top:10px;
  padding-bottom:10px;
  font-size:12px;
  font-family:arial;
  border: 1px solid #c4c0c0;
  color:#585858;
}
.trmy:nth-child(odd) {
  background-color:#F5F5F5;
}
tr:nth-child(even) {
  background-color:#ffffff;
}

Here is an image of my current table: https://i.sstatic.net/Yy3FD.png

I am constructing this table in JavaScript.

  
$(window).load(function(){
var customers = new Array();
customers.push(["TN04 AH 0253", "55"]);
customers.push(["TN04 AF 8830", "67"]);
customers.push(["TN37 CM 1249", "33"]);
customers.push(["TN19 F 9175", "47"]);
customers.push(["TN37CM 1932", "0"]);

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

var dateArray = getDates(firstDay, lastDay);

// Create an HTML Table element.
var table = document.createElement("TABLE");
table.setAttribute('class', 'tablemy');
table.border = "1";

// Get the count of columns.
var columnCount = customers[0].length;

var row = table.insertRow(-1);
for (var i = 0; i < dateArray.length; i++) {
    var headerCell = document.createElement("TH");
    if (i === 0) {
        headerCell.setAttribute('class', 'headcol');
    } else {
        headerCell.setAttribute('class', 'thmy');
    }
    headerCell.innerHTML = dateArray[i];
    row.appendChild(headerCell);
}

// Add the data rows.
for (var i = 0; i < customers.length; i++) {
    row = table.insertRow(-1);
    row.setAttribute('class', 'trmy');
    for (var j = 0; j < columnCount; j++) {
        var cell = row.insertCell(-1);
        if (j === 0) {
            cell.setAttribute('class', 'headcol');
        } else {
            cell.setAttribute('class', 'tdmy');
        }
        cell.innerHTML = customers[i][j];
    }
}

var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
})
function getDates(date1, date2) {
var day = 1000 * 60 * 60 * 24;
var diff = (date2.getTime() - date1.getTime())/day;
var dateArray = new Array();
dateArray.push("Unit/Count");
for(var i=0; i<=diff; i++)
{
    var xx = date1.getTime() + day * i;
    var yy = new Date(xx);

    var strDate = yy.getDate() + "/" + (yy.getMonth() + 1);
    dateArray.push(strDate);
}
return dateArray;
}

Answer №1

To ensure the 1st column stays fixed, you can set position: fixed. And to display all other columns, add padding-left: 130px; (equal to the width of the first column) for the .tablemy class:

function getDates(date1, date2) {
var day = 1000 * 60 * 60 * 24;
var diff = (date2.getTime() - date1.getTime())/day;
var dateArray = new Array();
dateArray.push("Unit/Count");
for(var i=0; i<=diff; i++)
{
    var xx = date1.getTime() + day * i;
    var yy = new Date(xx);

    var strDate = yy.getDate() + "/" + (yy.getMonth() + 1);
    dateArray.push(strDate);
}
return dateArray;
}

var customers = new Array();
customers.push(["TN04 AH 0253", "55"]);
customers.push(["TN04 AF 8830", "67"]);
customers.push(["TN37 CM 1249", "33"]);
customers.push(["TN19 F 9175", "47"]);
customers.push(["TN37CM 1932", "0"]);

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

var dateArray = getDates(firstDay, lastDay);

// Create a HTML Table element.
var table = document.createElement("TABLE");
table.setAttribute('class', 'tablemy');
table.border = "1";

// Get the count of columns.
var columnCount = customers[0].length;

var row = table.insertRow(-1);
for (var i = 0; i < dateArray.length; i++) {
    var headerCell = document.createElement("TH");
    if (i === 0) {
        headerCell.setAttribute('class', 'headcol');
    } else {
        headerCell.setAttribute('class', 'thmy');
    }
    //headerCell.setAttribute('class', 'thmy');
    headerCell.innerHTML = dateArray[i];
    row.appendChild(headerCell);
}

// Add the data rows.
for (var i = 0; i < customers.length; i++) {
    row = table.insertRow(-1);
    row.setAttribute('class', 'trmy');
    for (var j = 0; j < columnCount; j++) {
        var cell = row.insertCell(-1);
        if (j === 0) {
            cell.setAttribute('class', 'headcol');
        } else {
            cell.setAttribute('class', 'tdmy');
        }
        //cell.setAttribute('class', 'tdmy');
        cell.innerHTML = customers[i][j];
    }
}

var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
html, body {
  margin: 0;
  padding: 0;
}
.mydiv {
      overflow-y: scroll;
   }
  .headcol {
    position: fixed;
    left: 0;
    width: 100px;
    text-align:center;
    background-color: #4CAF50;
    color: white;
    font-family:arial;
    font-size:13px;
    padding-left:15px;
    padding-right:15px;
    padding-top:10px;
    padding-bottom:10px;
    border: 1px solid #c4c0c0;
}

.tablemy {
    border-collapse: collapse;
    border: 1px solid #c4c0c0;
    margin-left: 130px;
}

.thmy {
    text-align:center;
    background-color: #4CAF50;
    color: white;
    font-family:arial;
    font-size:13px;
    padding-left:15px;
    padding-right:15px;
    padding-top:10px;
    padding-bottom:10px;
    border: 1px solid #c4c0c0;
}

.tdmy {
    white-space: nowrap;
    padding:8px; border-left:1px solid #ccc; border-top:1px solid #ccc;
    padding-left:15px;
    padding-right:15px;
    padding-top:10px;
    padding-bottom:10px;
    font-size:12px;
    font-family:arial;
    border: 1px solid #c4c0c0;
    color:#585858;
}
.trmy:nth-child(odd) {
    background-color:#F5F5F5;
}
tr:nth-child(even) {
    background-color:#ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="dvTable"></table>

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

Adjust the color of text as you scroll

Could you provide guidance on changing the color of fixed texts in specific sections of my portfolio website? Unfortunately, I can't share my lengthy code here, but would greatly appreciate it if you could illustrate with examples. Here's a refer ...

Using the power of jQuery to load Ajax content, unfortunately, the content remains

Hey there, I'm currently working with an HTML file that utilizes AJAX to load content from other HTML files on the same server. However, for some reason, it's not functioning properly. I'm new to AJAX and I'm not sure what could be caus ...

Controlling Formatting in ASP.NET

Feeling puzzled by a seemingly simple question with no clear solution in sight. We're attempting to transition an interface to an ASP.NET control that currently appears like this: <link rel=""stylesheet"" type=""text/css"" href=""/Layout/CaptchaLa ...

Shifting annotations on a Bar Graph featuring Negative Values on Google's Chart Maker

Incorporating google charts into my MVC project. Looking to create a bar chart that accommodates negative values. Desire annotations on the same side as the end of the bar for negative values (similar to positive values shown in the green box below). ht ...

The rendering of the font appears distinct when viewed on an iPad compared to when displayed

Visit this website. The menu displays correctly on desktop, but on iPads, the font appears larger leading to a line break. Is it because the selected font isn't loading and defaulting to Times New Roman instead? It seems likely since I experience the ...

Is it possible to incorporate Excel files into a web-based system that only supports HTML?

Currently, I am working on an HTML-based system where my supervisor has specified that only HTML can be used to keep things easy and simple. My question is: Can Excel files be added to the HTML-based system, and if so, is it possible to work with, save, a ...

CSS - Maximizing One Column's Width While Allocating Percentage Space for Two Columns?

It's been quite some time since I delved into the world of web development and I seem to have forgotten how to tackle this particular issue. Despite hours spent searching online, I've gained knowledge about flex-boxes and other useful tools, but ...

How can you vertically center an icon button in Material UI?

Looking for help with aligning elements in this code snippet: <TextField id="outlined-basic" label="22Keyword" defaultValue={"test123"} variant="outlined" /> <IconButton aria-label="delete&q ...

Hide elements in hidden divs until the page is fully loaded to reduce initial page

www.prismasites.com I am creating a unique world map by using SVG DIVs shaped like Continents. Upon clicking on a continent on the world map, it conceals the world map DIV and displays the respective continent DIV with SVG. I have successfully achieved ...

Attempting to limit entry to a pathway when the loggedIn criterion is satisfied

I am currently facing a challenge with restricting access to the login page if the user is already logged in. I have been attempting to achieve this by checking for an existing token in the localStorage. Do you have any suggestions on how I can troublesh ...

Popover disappears when scrolling the page, but its position remains constant in Angular 4+

After clicking on an icon, a popover appears. I've noticed that the popover has a delay set, but when I scroll, the popover also moves along with it. Is there a way to keep the popover in place and not have it affected by scrolling? <md-badge cla ...

Modifying the state object in ReactJS: A step-by-step guide on updating values

Below my query and explanation, you will find all the code. I am currently attempting to update the state in a grandparent class. This is necessary due to file-related reasons, and I am using Material-UI for text boxes. Additionally, I am implementing Red ...

Conceal overflow in SVG after stroke is applied to top rectangle border

Is there a way to conceal the overflowing red color in this SVG? I attempted repositioning it before the rect with the stroke, but that didn't solve the issue. Check out the code and screenshot below. <br><br> <svg _ngcontent-fdl-c1 ...

When removing the class "img-responsive" from an image, the bootstrap columns begin to overlap

Just starting out with Bootstrap while working on an Angular2 project and I have a question. Currently, I have a map-component taking up 3 columns on the left-hand side, but every time I resize the browser, the image also resizes. I want the image to rema ...

Angular 8 fails to retain data upon page refresh

I have a property called "isAdmin" which is a boolean. It determines whether the user is logged in as an admin or a regular user. I'm using .net core 2.2 for the backend and Postgre for the database. Everything works fine, but when I refresh the page, ...

Steps for triggering a click event on a div with a button role within a class containing multiple elements

Can anyone help me figure out how to auto-click every button in Instagram's "hide story from" settings using console? I tried the following code: for (let i = 0; i < 300; i++) { document.getElementsByClassName('wbloks_1')[i] ...

Photographs within a line of HTML tables

I have been struggling with this issue, and it's honestly such a simple mistake! All I need is for each picture to be accompanied by a small box below it containing the name. I want all 4 pictures to be displayed in a row. However, when viewing this ...

The website on iPad automatically zooms in upon opening and then increases the zoom level even further when a specific button is tapped

I recently coded a website using html, css, and js. It seems to work perfectly on all devices except for the iPad. Interestingly, when I use the iPad emulator in Google Chrome, everything appears normal. However, when I open the website on an actual iPad, ...

Challenges with Knockout.js Virtual Elements in Different Environments

I am facing a peculiar issue where a virtual knockout template fails to bind correctly when accessed remotely, yet functions perfectly when viewed locally. You can find the problematic page here: Here is the template I am using: <ul> <!-- k ...

Maximizing the Potential of Bootstrap 5's Grid System

I'm struggling a bit with the Bootstrap grid system. I want to create 6 divs or containers that span the full width on smaller devices like mobiles, use 25% of the width on medium devices like tablets, and display all 6 in a single row on large deskto ...