Create a CSS style that locks the first column of a table in place while allowing the rest of the columns to scroll horizontally on an HTML webpage

There are numerous solutions available for creating a table with frozen columns and scrollable content, such as:

how do I create an HTML table with fixed/frozen left column and scrollable body?

However, my specific requirement is to have the scroll bar on the page (body) itself rather than on the table or any surrounding container.

Edit- It's just a simple HTML table that exceeds the display size, requiring a horizontal scroll. Placing the horizontal scroll on the body of the page eliminates the need for users to scroll to the bottom before accessing it horizontally.

        .stickyCol2 tr th:nth-child(1),
        .stickyCol2 tr td:nth-child(1){    
          position: absolute;
          width: 50px;
          left: 15px;
          top: auto;  
          background-color: #fff;
        }

        .stickyCol2 tr th:nth-child(2),
        .stickyCol2 tr td:nth-child(2){    
          position: absolute;
          width: 60px;
          left: 86px;
          top: auto;  
          background-color: #fff;
        }
 <div class="stickyCol2">
            <table>
               <thead>
                  <tr>
                     <th>item 1</th>
                     <th>item 2</th>
                     <th>item 3</th>
                 </tr>
              </thead>
              <tbody>        
                 <tr>
                   <td>item 1</td>
                   <td>item 2</td>
                   <td>item 3</td>
                </tr>
             </tbody>
         </table>
         </div>

Check out the js fiddle version here: https://jsfiddle.net/uthz6c24/1/

Answer №1

Here you will find a practical solution with code examples that can be adjusted to suit your specific needs.

The key concept is to enclose the fixed columns within span elements, position them on the left side of the screen using CSS, and set their width based on their content. In my code example, I focused on a single column for simplicity.

var cellWidth=$('th:first-child').width();
$('th:first-child, td:first-child').each(function() {
  $(this).wrapInner('<span></span>');
  $(this).find('span').attr('style', 'width:'+cellWidth+'px;');
})

To prevent overlap between the fixed columns and scrollable content, add a margin-left to the table equal to the combined width of the fixed columns (calculations may be required using Javascript).

$('table').attr('style', 'margin-left:'+cellWidth+'px;');

Utilizing jQuery, monitor the body's scroll event (or equivalent for an overflowing container) and apply a negative transform:translateY property to the spans.

$(window).on('scroll', function() {
  var scr = -$(this).scrollTop();
  console.log(scr);
  $('th:first-child span, td:first-child span').css('transform', 'translateY(' + scr + 'px)');
})

Please refer to this working fiddle for a hands-on demonstration and potential inspiration. https://jsfiddle.net/scooterlord/ndxjg1b0/21/

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

What is the method for creating a loop that includes a radio-like button?

https://i.stack.imgur.com/YkheU.jpg How can I create a button that functions like a radio button? What is this type of button called? And how can I add radio buttons in a loop similar to the image above? I know the button input needs to be wrapped with ...

When the canvas is dragged, an item within it suddenly leaps or bounces

I've noticed that when I drag the canvas using -webkit-transform: translate(x,y), an element on the canvas jumps. Are there any suggestions for addressing this issue? ...

Retrieving data from a database in PHP and assigning it as the value for an HTML select tag

Seeking assistance on a project to develop a stock management system for an herb factory using PHP with a MySQL database. Currently working on a page that allows the user to edit the value of a bench containing herbs. The bench details have been stored in ...

Enhancing Title and Meta Tags with Decorative Styles

Looking to style the <title><p>AAA</p></title> and <meta name="decrition" content="AAA">. But when I added <p> and applied CSS with: p{color:red;size:1000px} The title is being displayed as <p>AAA</p> Any ...

How to style the first column of the first row in a table using CSS without affecting nested tables

Having some challenges with CSS selectors, I'm hoping to find some assistance here. Presented with HTML code that resembles the following: <table class=myTable> <tr> <td>this is the td of interest</td> </tr> ...

Exploring the semantic-ui dropdown menu feature in Chrome

When I first started learning to code with semantic-ui framework, I noticed a difference in behavior in Chrome compared to other browsers. The pointing menu on the left element (such as the search box) breaks down in Chrome, whereas it displays correctly i ...

What is the best way to trigger a jQuery animation when a section becomes visible using Fullpage.js?

Within my website, I've incorporated Fullpage.js and am interested in triggering jQuery animate functions as users scroll to specific sections. Although I tested methods like mouseenter, mouseover, and mouseleave from the prior section, they did not d ...

Opacity in text shadow effect using CSS

Within my text lies the following css snippet: .text-description-header { font-size: 250%; color: white; text-shadow: 0 1px 0 black; } Observe the dark shadow effect it possesses. Inquiry I am curious if there is a way to alter the shadow t ...

The absence of a scroll bar on the web application is preventing me from scrolling properly

The vertical scroll bar on my Angular app seems to have disappeared mysteriously. I haven't made any changes to the code recently, and I'm struggling to figure out why it's missing. I've spent days trying to troubleshoot this issue with ...

Error message: ngRepeat does not allow duplicate elements in an array

Upon review, I discovered this particular piece of code: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <script> var app = angular.module("myS ...

A Guide to Importing CSV Data Into a Datatable

Is there a way to efficiently import data from a CSV file and display it in a table using the datatables plugin? Currently, I have a fixed table structure: <table id="myTable" class="table table-striped" > <thead> ...

What could be the reason behind the issue of my HTML draggable feature not functioning properly on touch

I've set up a draggable div with headers and p tags, but I'm encountering an issue when trying to run it on a touch screen. The div tag isn't draggable in this scenario. Can anyone suggest the best solution for making this page touch screen ...

Is it frowned upon or considered incorrect to achieve a horizontally centered page by adjusting the CSS properties of the html tag?

Is it considered wrong or frowned upon to center a webpage horizontally by adjusting CSS properties of the HTML tag? Sample CSS code: <style type="text/css"> html { width: 1200px; margin: 0px auto; background-color: ...

Using AngularJS to bind radio buttons to ng-model

Here is a snippet of my HTML code where I attempted to bind the "formFriendsAll" scope to the ng-model. <form ng-submit="submitForm()" > <div class="col-sm-3"> <div class="form-group"> <label>Which Persons to show?< ...

Move to Fieldset Upon Link Click

Here's an example of what I have implemented so far here It's evident that this is not fully functional due to the PHP and jQuery integration. This demo is just a showcase of my progress. I am looking to create a functionality where clicking on ...

Challenges with looping in Jquery animations

I've been working on an animation function that I want to run in a loop. So far, I've managed to get it to work for one iteration, but I'm struggling to figure out how to repeat the loop a specific number of times. Below is the code for my a ...

The conversion of a newline in an Angular page is done using &lt;br/&gt tag

Here is a function I have: setLocalVariableOnAccepted(ogp, hb, responseJson) { if (responseJson.ofgp === undefined) { this.ogpStatus = 'orange'; this.ogpStatusMsg = responseJson.ofgp + ', <br/> No change. Previous va ...

I would like for my element to increase and decrease in size while rotating when the button is clicked

I am trying to create an element that changes its size while spinning when a button is clicked. It seems to be working fine on hover, but not onclick. Here is the code I have: <div class="rec">Rec</div> <button id="button&quo ...

What is preventing the Navbar from aligning to the right side in Bootstrap 5?

I'm trying to position only the "Account" navbar all the way on the right side using ms-auto, but it doesn't seem to be working correctly. Here's my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="u ...

Position a grid item in the center

Can someone help me with centering my container's item? I am struggling to align the third item to the center using display: grid. Previously, I attempted to use flexbox but found it to be less effective for a responsive layout. .projetos { f ...