When using position:sticky, the overflow:auto behavior may not function as intended

My Bootstrap table has the class "table-responsive," which automatically sets overflow-x to auto when the table is too wide for the screen.

In addition, I've applied the class "sticky-top" to the th elements in order to make them sticky within the table.

According to a response on Stack Overflow, setting the parent of the sticky element to overflow can cause it to become the scrolling container instead of the window.

Currently, I only apply overflow to the table-responsive class when necessary using a media query:

.table-responsive{
   overflow-x:inherit;
}

@media (max-width:432px){
   .table-responsive{
      overflow-x:auto;
   }

The problem now is that the table header does not stick on mobile screens.

Answer №1

To address this particular issue, I integrated elements from Rik Schennink's approach and also drew inspiration from Dannie Vinther's method as well. In my scenario, I decided to duplicate the table headers, naming them "responsive-header." By default, this "Responsive-header" is set to not be displayed using display:none. Once the original header goes out of view due to scrolling, the responsive header becomes visible.

Below is a simplified version of what I've implemented:

HTML
<html>

  <body>
    <main>
      <section>
        <table id="respond" class='table table-responsive sticky-top responsive-header'>
          <thead class="thead-dark">
            <tr>
              <th class="sticky-top">sticky</th>
              <th class="sticky-top">sticky</th>
              <th class="sticky-top">sticky</th>
              <th class="sticky-top">sticky</th>
              <th class="sticky-top">sticky</th>
              <th class="sticky-top">sticky</th>
            </tr>
          </thead>
        </table>
        <table class='table table-responsive'>


          <thead class="thead-dark">
            <tr>
              <th class="sticky-top">sticky</th>
              <th class="sticky-top">sticky</th>
              <th class="sticky-top">sticky</th>
              <th class="sticky-top">sticky</th>
              <th class="sticky-top">sticky</th>
              <th class="sticky-top">sticky</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>test</td>
            </tr>
            <tr>
              <td>test</td>
            </tr>
            <!-- Additional rows omitted for brevity -->
          </tbody>
        </table>
      </section>
    </main>
  </body>

</html>

CSS

.table {
  width: 100%;
  margin-bottom: 1rem;
  color: #212529;
}

.table .thead-dark th {
  color: #fff;
  background-color: #343a40;
  border-color: #454d55;
}

.table-responsive {
  display: block;
  width: 100%;
  overflow-x: auto;
}

.sticky-top {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  z-index: 1020;
}

.responsive-header {
  display: none;
}

jQuery Implementation

function debounce(func, wait, immediate) {

  var timeout;

  return function() {

    var context = this,
      args = arguments;

    var later = function() {
      timeout = null;

      if (!immediate) func.apply(context, args);

    };

    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);

    if (callNow) func.apply(context, args);

  };

}

const storeScroll = () => {
  document.documentElement.dataset.scroll = window.scrollY;
  if (window.scrollY >= 10) $('#respond').removeClass('responsive-header');
  else $('#respond').addClass('responsive-header');
}
document.addEventListener('scroll', debounce(storeScroll), {
  passive: true
});
// Update scroll position for first time                                                                                                                                                    @
storeScroll();

For further reference, here is the corresponding jsfiddle:https://jsfiddle.net/uf468ocy/

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

Creating consistent indentation in HTML code can be achieved without the presence of any unnecessary

When I add indentation to my HTML code, it results in extra whitespace between elements on different lines. <div id="nbcntcnt"> <a href="notset.html" class="nbcntbutton" id="snbb">Overview</a> <a href="notset.html" class="nbcntb ...

Is using tables still considered a recommended practice for organizing a layout such as the one shown in the [IMG]?

Looking for recommendations on arranging images in the footer, in line with the design mockup using HTML/CSS. Wondering if tables are still a viable option for this purpose? ...

Creating HTML code from a website by utilizing XML

As someone who is not a developer and doesn't have much knowledge about java, I am seeking advice on potential solutions to achieve the following. This web hosting service enables users to retrieve data from their XML spreadsheets and embed them anyw ...

When I hover over the navigation bar, a submenu pops up. However, as I try to navigate to the submenu, I often end up accidentally selecting a different item on the navigation bar

I'm trying to find an answer but can't seem to remember where I saw it. Here's the situation: a horizontal nav bar with a dark blue selection and a red sub-menu. When the user hovers over a black arrow, it crosses into a light-blue nav item ...

Step-by-step guide on eliminating the modal post-validation

Newbie in reactjs looking for help with modal validation issue. Goal: Press submit button inside modal, validate, then close the modal. Want to reuse modal for another row. Problem: I'm having trouble making the function work for a new row after ...

I'm struggling to convert this vertical navigation bar into a horizontal layout using CSS

<nav class="navbar navbar-dark bg-dark sticky-top"> <a class="navbar-brand" href="#">I/H</a> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> ...

Is the component experiencing issues with its style functionality?

I am attempting to add CSS styles to app.component.ts using the :host property, but I am not seeing the desired results. The CSS is being applied, but not correctly. .ts export class AppComponent { title = "Default Title" data = 'This is defaul ...

What's the best way to toggle the visibility of an input-group in Bootstrap?

Is there a way to properly hide and show a Bootstrap 5 input-group? You can see an example here: https://jsfiddle.net/o08r3p9u I'm facing an issue where once the input group is hidden, it doesn't show correctly when displayed again. How can I e ...

What's the best way to add line numbers to source code on an HTML webpage after parsing?

I am currently working with AngularJS and MongoDB. In my MongoDB data, there are some text elements that contain a \n, causing each line to be displayed on a new line based on the occurrence of \n. However, I also want to add line numbers to each ...

Is the "data-export-data-type="all" parameter not functioning properly for exporting data from all pages within the bootstrap table plugin?

I'm currently utilizing the bootstrap table extended in conjunction with bootstrap 4. My goal is to utilize the export button to download data from all pages. The CSS file being used is: <link rel="stylesheet" href="https://unpkg.co ...

Is it possible to create an HTML select that displays transparent text after a selection

I'm currently working on customizing the appearance of an HTML select element with various background color options. Everything is functioning properly, but I have a specific requirement. I want the text in the dropdown options to be visible only when ...

Problems with JQuery UI buttonset behavior

As I develop a UI application utilizing JQuery UI components, I encounter an issue with aligning radio buttons within the interface. While using JQuery buttonset in isolation functions correctly, integrating it with other UI elements causes misalignment: ...

Problem with items overlapping in hoverable drop-down menu

I have been attempting to create a hoverable dropdown menu, but I am encountering an issue where the items of the dropdown are overlapping. Despite my efforts to adjust the CSS classes, I have not been successful in fixing this problem. Additionally, I ha ...

"Customize your WordPress theme by moving the sidebar from left to right for

Currently, I am utilizing the flat theme sourced from . In an attempt to customize the appearance, I made modifications within style.css: #page:before, .sidebar-offcanvas, #secondary {float: right !important;} However, this adjustment only applies to a ...

Using jQuery to alter the properties of CSS classes

Is it possible to modify the properties of a CSS class, rather than the element properties, using jQuery? Here's a practical scenario: I have a div with the class red .red {background: red;} I wish to change the background property of the class re ...

Troubleshooting problem with div width in Outlook causing table cell padding issue for curved corners on another div

This question has significantly evolved following additional testing I am using a table layout similar to this: <table> <tr> <td></td> <td style="padding:10px 3%;"> <div border="2px solid #000000;"> ...

Photo on vertical display

I have been working on displaying dynamic photos from a backend file and looping through them. I have successfully displayed the images vertically using CSS. vertical-align: middle; However, when I tried to add a photo name for each image, the positionin ...

Utilize the object's ID to filter and display data based on specified criteria

I retrieved an array of objects from a database and am seeking to narrow down the results based on specific criteria. For instance, I want to display results only if a user's id matches the page's correct id. TS - async getResultsForId() { ...

Incorporating a classList.toggle into a snippet of code

button, p, h1, h2, h3, h4, h5, a{ /* Define specific elements to use "fantasy" font */ font-family: Tahoma; } #main_body{ margin: 0px auto; background-color: #dedede; } #top_body{ /* Remove margin for simplicity */ } #t ...

To view the following set of three images, simply click on the "load more" button

I'm looking to add a load more button to reveal additional images. Currently, the page loads with 3 images visible, and upon clicking the load more button, the next set of 3 images should be displayed on the screen. Unfortunately, the code I've ...