Maintain the header of a table at the top of the grid as you scroll

Although I know there are multiple ways to write this code, I have attempted (and fixed) it. Since I'm not well-versed in front-end development, I am finding this task to be quite challenging. I discovered that placing the table header within a table itself and setting the table body to scrollable -y worked for me. However, I also need to align columns based on a user's selection from a dropdown menu. If I could find a solution without having to do that, it would greatly enhance the appearance of the table, but so far, I haven't found a fix for it.


      <div v-if="globals.showStructure === true" style="border: 1px solid red; max-height:500px; overflow-y:scroll; position: top;" id="tableContainer2">
        <table class="table table-bordered">
          <ul class="right-click-menu" tabindex="-1" v-if="globals.viewActiveStructMenu === true" ref="activeStructure">
            <li v-on:click="deleteStructure()">Delete</li>
            <li v-on:click="pendStructure()">Pend</li>
          </ul>
          <ul class="right-click-menu" tabindex="-1" v-if="globals.viewPendStructMenu === true" ref="pendStructure">
            <li v-on:click="deleteStructure()">Delete</li>
            <li v-on:click="activateStructure()">Activate</li>
          </ul>
          
          <thead>
            ...
              <th>Your Header Text Here</th>
            ...
          </thead>

          <tbody>
            ...
              <td>Your Data Here</td>
            ...
          </tbody>
        </table>
      </div>

Your CSS can be included here if necessary for styling purposes.

Answer №1

Utilize the new position: sticky property to make elements stick at the top of the page when scrolled over.

To achieve this, specify a top value to set the offset (often 0).

Keep in mind that the sticky property may not work across all browsers and can be buggy within tables: https://caniuse.com/#feat=css-sticky

thead {
  /* position: sticky; and top: 0; are the only needed properties here. The rest is for showcase only. */
  position: sticky;
  top: 0;
  background: red;
}

th {
  width: 300px;
  height: 50px;
}

td {
  border: 1px solid yellow;
  height: 200px
}
<table>
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A</td>
      <td>B</td>
      <td>C</td>
    </tr>
    <tr>
      <td>A</td>
      <td>B</td>
      <td>C</td>
    </tr>
    <tr>
      <td>A</td>
      <td>B</td>
      <td>C</td>
    </tr>
    <tr>
      <td>A</td>
      <td>B</td>
      <td>C</td>
    </tr>
  </tbody>
</table>

Answer №2

Back in the day, I tackled this issue by utilizing a fixed table layout CSS with only one column allowed to expand width. The solution involved using a pair of tables - one for headers and the other for rows, enclosed within a scrollable DIV. Although this method was implemented around 10 years ago, it was tailored to be compatible with IE6.

In the present time, you can achieve a similar effect by applying CSS to your <tbody>, setting overflow-x:none and overflow-y:scroll (or auto for shorter data lists), ensuring that your <tr> elements remain within the <tbody>.

(I've made an edit to include formatting with the code tag to prevent HTML tags from disappearing in the text!)

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

Position text input boxes on the right side of the div element

I am seeking help with aligning the text inputs to the edge of .formColumn2 so they appear in a neat line together. I have attempted using margin-right:0 and margin-left, but these solutions end up extending the .formColumn2 div which is not my desired out ...

Safari iOS does not display any background for Buttons

Encountering an unusual problem with buttons on iOS devices specifically in Safari browser - the background color isn't being applied like it is on Desktop and Android devices. Here are the CSS properties for the button: export const Button = styled.b ...

Creating a sort button in HTML that can efficiently sort various divs within a table is a useful tool for enhancing user experience

My HTML table is populated with various <td> elements. How can I arrange these divs based on IMDb rating, TomatoMeter, etc... [ CSS code is not provided below ] <table> <tr class="row"> <td class="column"> <br> ...

"An issue with IE9 causing small dots on rounded corners during rendering

Help Needed: Strange IE9 Rendering Issue I'm experiencing an odd rendering problem in Internet Explorer 9. You see those little white dots on the left? What could be causing them? Any suggestions on how to remove them? Microsoft, why always so myst ...

PHP: Retrieving a selection value without the use of a submit button

I am trying to access and utilize the select value in my current PHP file, but without the use of a submit button. How can I accomplish this? Here is the code snippet I am working with: <?php $args = array( 'orderby' =&g ...

The server's file URLs are modified within the page source of a WordPress site

I've been attempting to integrate Adsense code into a WordPress blog at demonuts.com. I placed the Google code in the TEXT WIDGET provided by WordPress. However, upon running the website, I noticed that the URLs for .js, .css, or .png files are being ...

The data from the Subscribe API call is gradually loading within the ngOnInit() function

When using Angular 8, I am experiencing slow data retrieval when making API calls in the ngOnInit() function. The issue arises when trying to pass this data as @Input from one component module to another - it initially comes through as undefined for a minu ...

Using ExpressJS and Jade to submit a form using the POST method and redirecting to a specified path

I am exploring node, express and jade for the first time and working on a small application that requires users to enter their name and password in a form. The app then redirects them to a path based on their username. Here is the code snippet to achieve ...

Updating an AngularJS directive with a change in URL: Best practices

Similar Question: Customizing tab styles in AngularJS Utilizing AngularJS, I am attempting to include a "current" class in my menu item whenever the content of that tab is being shown. The current implementation works as expected upon page load: HTML ...

Obtaining identifier through class when clicked

I have written some code that is supposed to display an alert of the <a> element's id using the class name when clicked. However, I am always getting an alert for tuto1. Can someone please help me figure out what is wrong? $(document).ready(f ...

Implementing onMouseEnter and onMouseLeave functionalities for music player

Currently facing a challenge while developing a music player app. I am trying to implement a feature where: Upon hovering over a song, a "play" button should appear in place of the song number. The currently playing song should display a "pause" ...

What methods can users employ to effectively manage and maintain their in-app purchases using my application?

Hey there, I could really use some assistance. Recently, I created a mobile app for a client that allows users to purchase and watch video courses. However, I'm facing an issue where when a user buys a course and then refreshes the app, they are redir ...

Creating a model with a many-to-many association using Sequelize

Technologies Stack: NodeJs, PostgreSQL, Sequelize, Express. I am working with two linked models (User and Role) through the intermediary table User_Roles. While creating a new user using Sequelize.create(), I need to populate the User_Roles table to specif ...

What is the process for extracting Html sub elements from parent elements?

While using my HTML editor, specifically the Kendo Editor, to generate bullets and indent them for sub-bullets, I noticed that the HTML output wasn't as expected. <ul> <li>Focusing on lifetime income replacement <ul>< ...

Issue encountered with Node's Google Page Speed API implementation

I am facing difficulties in using the Node client for Google PageSpeed API. Every time I run node index.js in the command line, I encounter the following error: /Volumes/folder/pagespeed/index.js:7 }).then(function(res) { ^ TypeError: Cannot read pro ...

How can I alter the background color of the entire header in Ionic?

Having some trouble changing the color of my header. I successfully changed the color of the white header, but not the black header where the time is displayed. I know this is beyond Ionic and part of Android, but I have seen other apps that are able to ch ...

Vue.js $scopedSlots do not function with Vue object

In the process of developing a Vue component that will be released once completed, I am wrapping Clusterize.js (note that the vue-clusterize component is only compatible with v1.x). The goal is to efficiently render a large list of items using Vue, particu ...

What is the process for importing a Kaggle dataset into Elasticsearch?

Having just started with elasticsearch, I am venturing into creating a movie search application. My plan involves sourcing data from kaggle and integrating it into my locally set up elasticsearch at localhost:9200. Upon visiting the localhost link, I came ...

The Stripe card element seems to be missing from the form

I'm a newcomer to angularjs and currently working on integrating version 3 of the stripe api into my angular application. I followed the steps provided on the stripe website, but faced an issue when trying to incorporate their code which is primarily ...

You can't send headers to the client in Express after they have already been set

I successfully registered and inserted a record in my MongoDB. However, I encountered an error when trying to log in at the line "!user && res.status(401).json("Wrong User Name");" Cannot set headers after they are sent to the client at new NodeError ...