Table header sticking does not work when overflow is set to scroll or auto

After trying numerous solutions without success, I am reposting this question. My table has a horizontal scroll and I attempted to make the table header sticky using position:sticky, but it caused the scrolling functionality to stop working.

Is there a way to achieve both functionalities with just CSS?

Feel free to refer to this simple Fiddle for context.

update I require the table body scrollbar to behave the same as the main page scroll. Any pure JS or Angular solution is also acceptable. The header should remain sticky when the user scrolls through the page, not just the table itself.

Answer №1

For those who are committed to using only CSS, one way to make the header stick within a responsive div is by adding a specified height to the 'responsive' class.

An alternative approach would be to replace the table element with separate divs for headers and body sections.

Answer №2

    .adaptive {
    width: 500px;
    max-height: 80vh;
    overflow-y: auto;
}

Implementing this can assist in achieving the intended functionality.

Answer №3

Do we really need to use div.responsive? Here's an alternative solution.

I decided to include a <thead> and <tbody> to separate the header and body sections.

<thead> and <tbody> each have their own scroll bar. To ensure that the set width is applied to <thead>, I used display: block:

thead,
tbody {
    display: block;
    overflow-x: scroll;
    width: 400px;
}

To guarantee equal cell widths, I added min-width to all cells with a reasonable value:

th,
td {
    text-align: left;
    padding: 8px;
    min-width: 70px;
}

To make the header sticky, I utilized position: sticky on <thead> and hid the scrollbar. A JavaScript snippet was included to synchronize horizontal scrolls:

thead {
    overflow-x: hidden;
    position: sticky;
    top: 0;
}

const thead = document.querySelector('thead');
const tbody = document.querySelector('tbody');

tbody.addEventListener('scroll', () => {
  thead.scrollLeft = tbody.scrollLeft;
})
table {
  border-collapse: collapse;
  border: 1px solid #ddd;
}

thead,
tbody {
  display: block;
  overflow-x: scroll;
  width: 400px;
}

thead {
  overflow-x: hidden;
  position: sticky;
  top: 0;
}

th,
td {
  text-align: left;
  padding: 8px;
  min-width: 70px;
}

th {
  background-color: #000;
  color: white;
}

tr:nth-child(even) {
  background-color: #f2f2f2;
}
<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>

  <h2>Responsive Table</h2>
  <p>If you have a table that is too wide, you can add a container element with overflow-x:auto around the table, and it will display a horizontal scroll bar when needed.</p>
  <p>Resize the browser window to see the effect. Try removing the div element to observe changes in the table appearance.</p>

  <table>
    <thead>
      <!-- Header row data goes here -->
    </thead>
    <tbody>
      <!-- Body row data goes here -->
    </tbody>
  </table>

</body>

</html>

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 best way to incorporate a massive HTML string into a WebView using the LoadHTMLString technique?

I am struggling to display an HTML string on a UIWebView using the 'LoadHTMLString' method. Below is the code snippet I am using: [wv loadHTMLString:[NSString stringWithFormat:@"<!DOCTYPE html><html><head><meta name=\" ...

methods for transforming JSON array output objects into individual non-array values

I'm facing an issue with a JSON result that contains latitude and longitude as an array like [13.0801721, 80.2838331]. I need help in converting this to comma-separated values without the array brackets, similar to 13.0801721, 80.2838331. This is my ...

Initiate CSS3 animations on each individual slide within the slider

I have integrated flex slider into my project. There are 3 CSS3 animations implemented, where the animations work perfectly on the first slide when the website loads. However, upon switching to the second slide, the animations do not start. I am seeking ...

The apploading feature in my React Native is not functioning correctly, so I am unable to use it as intended

Every time I run my code, I encounter this error: error screenshot This is the code snippet I am using to import custom Google fonts: import React, { useState } from "react"; import Home from "./screens/home"; import { View } from &quo ...

What is the best way to retrieve a PDF file from another website and showcase it on our own site without any redirection?

Is there a way to display a pdf from another website without having to redirect to that site? I'm looking for a solution that involves using the URL directly. ...

Issues arise when props do not get transferred successfully from the getStaticPaths() to the getStaticProps

I have successfully generated dynamic pages in nextJS from a JSON using getStaticPaths(). However, I am facing an issue where I am unable to access the information within the JSON. I pass it as props to getStaticProps(), but when I try to console log it, i ...

Tips for ensuring that the lightbox scrolling feature only affects the lightbox and not the entire page

Currently, I am utilizing the lightbox_me jQuery plugin to trigger a lightbox when a user clicks on a product. The issue I am facing is that the lightbox content often extends below the visible area, causing the entire page to scroll when using the right s ...

What is the best way to activate an alert or swal function just once instead of repeatedly?

I am just starting to learn Angular. Currently, I have an application that contains two variables related to the status of financial transactions. These variables are: tab1TrxMessage, which holds any important messages, and tab1TrxStatus that indicates wh ...

trouble seeing images with an array input and ngFor in Angular

I am encountering issues while attempting to exhibit an array of images by their source link using ngFor. It seems like there are errors hindering the functionality! Below is the image HTML code located within my card component: <div class="Session-Pa ...

The button functionality gets hindered within the Bootstrap well

I'm trying to figure out what's wrong with my code. Here is the code: https://jsfiddle.net/8rhscamn/ <div class="well"> <div class="row text-center"> <div class="col-sm-1">& ...

Innovative react route

Currently, I am in the process of learning about dynamic react routes. In the code example I am working on, there are different buttons for each task. The goal is to render the WorkDetails component when a button is clicked. However, it seems to not be fun ...

Creating unique identifiers in Knockout.js based on text bindings

I am trying to achieve something similar to the code snippet below: <!-- ko foreach: subTopics --> <div id='subtopic-name-here'> <!-- /ko --> Specifically, I want the ID of my div to be set as the name of the corresponding ...

Angular: The CORS issue continues despite configuring proxy.conf.json

I have tried several tutorials in an attempt to resolve my CORS issues, but unfortunately, I have been unsuccessful so far. My server setup is very basic - it responds to get 127.0.0.1:8080/hello by returning the string hello there for testing purposes. ...

Issue with Hidden Horizontal Scrollbar Functionality in JQuery Mobile Not Resolving

http://jsbin.com/UREQUbu/1/edit I have a header with 9 buttons. I managed to get the horizontal scrollbar to work, but I want it hidden yet still scrollable. I came across a JQuery plugin that worked perfectly for scrolling on my laptop, but unfortunately ...

Looking to display or conceal several divs according to the option selected from a dropdown menu?

I've been searching for a solution to my simple dropdown issue, but haven't had any luck in the forums. This is the code for the dropdown: <select id ="category_faq"> <option value="1">item1</option> <option value= ...

Only one ID is recognized by jQuery

I have a group of three checkboxes set up like this: <input id="image_tagging" class="1" type="checkbox" value="1" checked="checked" name="data[image_tagging]"> Now, I've created an AJAX function (which is functioning correctly), but it seems ...

Sending a div class as a parameter to a JavaScript function

Wondering if it's possible to pass a div's class into a JavaScript function. I'm using SquareSpace so adding an id to the div is not an option, but it works fine with divs that have ids. JQuery is already loaded. This is my current train of ...

Utilize Flexbox's column direction to ensure that all flex items within the same column have uniform height

Having trouble creating a responsive web page. Here are the specifics: Sharing my HTML and CSS code below: - <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA ...

Querying a Database to Toggle a Boolean Value with Jquery, Ajax, and Laravel 5.4

I am facing an issue with a button I created to approve a row in a table. It seems that everything is working fine when clicking the button, but there is no change happening in the MySQL database Boolean column. Here is the code for my button: <td> ...

Determine if the user has clicked on the Save or Cancel button within the print dialog box

Hello everyone, Can anyone help me figure out how to determine which button was selected by the user in a print dialog box? Thank you! ...