Dynamic Bootstrap Table with Fixed Header

I am customizing a Bootstrap table by adding CSS for a sticky header. My code snippet includes the following:

.table-sticky th {
  background: #fff;
  position: sticky;
  top: -1px;
  z-index: 990;
}
<div class="table-responsive p-0 mt-2">
  <table class="table table-sm table-striped table-hover table-sticky">
    <thead>
      <tr>
        <th>#</th>
        <th>Header</th>
        <th>Header</th>
        <th>Header</th>
        <th>Header</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1,001</td>
        <td>Lorem</td>
        <td>ipsum</td>
        <td>dolor</td>
        <td>sit</td>
      </tr>
      <tr>
        <td>1,002</td>
        <td>amet</td>
        <td>consectetur</td>
	<td>adipiscing</td>
        <td>elit</td>
      </tr>
    </tbody>
  </table>
</div>

The issue arises when I wrap the table in div.table-responsive. How can I make both the sticky header and responsive wrapper coexist?

Answer №1

It is impossible to have a position: sticky element within a .table-responsive without having to completely rewrite the latter.

To solve this issue, I opted for utilizing .table-responsive-sm to avoid compromising functionality when a responsive table is not required.

Answer №2

If you find yourself in a situation where you need this functionality, the solution is to write the code yourself. The JavaScript snippet below will help achieve the desired effect:

var element = document.getElementById("fixed-thead");
var parentElement = element.parentElement;
window.addEventListener('scroll', () => {
    var coordinates = parentElement.getBoundingClientRect();
    if (coordinates.y < 0) {
        element.style.transform = 'translate3d(0, ' + (-coordinates.y) + 'px, 0)';
    } else {
        element.style.transform = 'translate3d(0,0,0)';
    }
});

To implement this code, make sure to mark the thead of your table with the ID "fixed-thead", like so:

<thead id="fixed-thead">

The use of translate3d aids in enabling hardware acceleration, resulting in smoother performance. If the scroll event triggers too frequently when using the scroll wheel, consider implementing debouncing for better user experience.

If your table contains columns with fixed widths, you can opt for using position: fixed and top: 0. However, for tables with varying lengths, it is recommended to stick with translate3d for optimal results.

In case you need to apply this code to multiple tables on a page, utilize the following script:

function applyFixedHeader(element) {
var parentElement = element.parentElement;
    window.addEventListener('scroll', () => {
        var coordinates = parentElement.getBoundingClientRect();
        if (coordinates.y < 0) {
            element.style.transform = 'translate3d(0, ' + (-coordinates.y) + 'px, 0)';
        } else {
            element.style.transform = 'translate3d(0,0,0)';
        }
    });
}

var elements = document.querySelectorAll("{yourSelector, e.g. `.table-fixed` for the tables containing class `table-fixed`}");
elements.forEach(element => applyFixedHeader(element));

Answer №3

To ensure the table head is fixed without any additional CSS, simply remove the table-responsive class from the div and add the class "bg-white sticky-top border-bottom" to the table tag. Here's an example:

<div class="table">
  <table class="table">
   <thead>
    <tr>
     <th class="bg-white sticky-top border-bottom">FirstName</th>
     <th class="bg-white sticky-top border-bottom">LastName</th>
     <th class="bg-white sticky-top border-bottom">Class</th>
    </tr>
   </thead>
   <tbody>
     <tr>
       <td>John</td>
       <td>Cooker</td>
       <td>A1</td>
     </tr>
     <tr>
       <td>David</td>
       <td>Jeferson</td>
       <td>A2</td>
     </tr>
     ...
  </table>
</div>

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 correct way to denote a CSS class in SASS syntax?

Can you show me how to code this in SASS? .solo:hover > .solo-pane, .solo-pane.active, .solo-pane.lighten { opacity: 0.5; } I'm having trouble separating the classes using commas. ...

How can we stop the Bootstrap carousel from pausing when the mouse hovers over it and keep it cycling automatically?

Is there a way to stop the Bootstrap carousel from pausing when hovering with the mouse and instead have it continue cycling through items automatically? I've tried changing the pause argument from "hover" as mentioned in the documentation, but when ...

Attempting to link two JavaScript files, however, only one of them is functioning correctly

I'm currently experiencing an issue with my HTML page that involves calling two JS files for two different image sliders on the same website page. One slider works perfectly fine while the other does not. I'm confused as to whether it's perm ...

The Angular ng-repeat directive is populating a list with items, but the parameters enclosed in double curly braces

After calling an API, the response contains data in the following format: [{name: "ABC", age: 20}, {name: "DEF", age: 25}] Even though the $scope.names variable is assigned with the array from the API, when viewed in the browser, it displays 2 rows but th ...

Optimizing Open Graph tags for sharing WhatsApp links

I am utilizing Open Graph tags to optimize sharing on social media platforms. The image I have specified is 1200 x 630 pixels and displays correctly on Facebook as well as Whatsapp: <meta property="og:image" content="https://emotionathlet ...

The cascading style sheet does not have any effect on the layout of the tables within the

I am trying to apply a CSS style to give all tables on my HTML pages a 1px border width. However, for some reason, the borders are not showing up in my HTML files! What could be causing this issue? <!-- <style type="text/css"> --> body{backg ...

Unexpected behavior: getElementById returning URL instead of element

I created a function that accepts a thumbnail path as an argument, waits for the bootstrap modal to open, and then assigns the correct path to the thumbnail href attribute within the modal. However, when I use console.log with the element(el), it displays ...

How can I modify the content within a scoped `<style>` tag in Vue?

Is there a way to dynamically change the contents of a <style> block in my Vue component using Vue variables? Many commonly suggested solutions involve inline styles or accessing the .style property with JavaScript. However, I am looking for a metho ...

The Google Maps App fails to launch now

Recently, my map started experiencing issues. The problem seems to be related to the HTML using a javascript and css file that is loaded from Google Drive for display. However, when I directly load these files from my computer, it works perfectly fine. Bel ...

Mastering Data Transfer in jQuery: A Guide to Migrating Event Information from .on(dragstart) to

I need help with transferring information between an .on(dragstart) event and an .on(drop) event. However, when I run the code below in Chrome, I encounter an error message: 'Uncaught TypeError: Cannot read property 'test' of undefined' ...

The wget tool is capable of downloading CSS files that contain @import rules, however it overlooks

Currently utilizing the following command with wget: wget --page-requisites --convert-links -e robots=off \ --span-hosts --restrict-file-names=windows \ --directory-prefix=$ASSETS_DIR --no-directories http://myhost/home The HTML page ...

Tips for verifying the presence of a 3D model from Spline API within the DOM using Next.js

I am in the process of developing a brand new website and I have integrated a 3D model from spline, although it is taking quite some time to load. To improve user experience, I decided to implement a loader/Spinner. However, I'm facing the challenge o ...

Tips on confirming the completion of my form when the next button is pressed

I am working on a multi-step form with a jQuery script to split the forms. The first form has only one button - the next button, which takes the client to the next form. However, when I click on the next button in the first form, it moves to the next form ...

Utilizing Font Awesome within the `<fieldset>` element alongside Bootstrap 4 forms

When it comes to single-input forms in Bootstrap 4, a convenient method for incorporating font-awesome icons is by utilizing the input-group-addon class: <div class="input-group"> <span class="input-group-addon"> <i class="fa fa ...

Leveraging the X-Send module for efficiently delivering css, javascript, and image files

I am in the process of setting up a file server that currently serves downloadable files such as .doc and .zip perfectly using X-Send. Is it also possible to use X-Send for serving text-based (css/javascript) or image files? I believe this method is quite ...

Elements displaying outside of block 'a' tag

I have a set of <a> elements that are styled with display:block. These contain various nested <divs>, for example: <a href="#" class="sliderframe"> <div class="container-caption"> <div class="slider ...

jQuery Mobile panel buttons are functioning properly within a maximum width of 300 pixels

I have constructed a panel that adjusts its size based on the device's screen using responsive design techniques. The code for this panel is as follows: <div data-role="panel" data-position="right" data-display="overlay" data-theme="a" id="add-for ...

Issue with AJAX MVC HTML: jQuery value is not blocking API call

Upon clicking a button, I am triggering a web API call using AJAX. My form is utilizing JqueryVal for form validations based on my viewmodel data annotations. The issue I am facing is that when I click the "Listo" button in my form, it executes the API ca ...

Tips for avoiding word fragmentation in <pre> code blocks

pre { white-space: pre-wrap; /* CSS 3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ overflo ...

Perform a check on the state of the slideToggle using an if-else function and provide a report on the slideToggle state

http://jsfiddle.net/vmKVS/ I need some help understanding the functionality of slideToggle using a small example. After toggling for the first time, the options element changes color to green. However, I expected the menu element to turn red when I togg ...