What is the best way to create a Bootstrap table with a fixed header that stays in place

I am currently working on creating a Bootstrap table that is responsive. My goal is to have the table head scroll along with the table data when scrolling down, without setting a fixed height for the table. I want the page to expand naturally as more rows are added, so simply using overflow-y: scroll won't work for me.

Even trying to use position: fixed or position: sticky has not solved my issue.

This is the code snippet I experimented with:

.example {
  padding: 5px;
  margin: 5px 0;
  border-radius: 2px;
  background-color: #afc8f0;
  text-align: center;
}

thead {
  /* position: fixed; */
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col">

      <div class="example">
        ... Example ...
      </div>

      <div class="example">
        ... Example ...
      </div>

      <div class="example">
        ... Example ...
      </div>

      <!-- ...
        Some other elements
        .. -->

      <table class="table table-striped table-hover table-sm">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">First</th>
            <th scope="col">Last</th>
            <th scope="col">Handle</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <th scope="row">1</th>
            <td>Mark</td>
            <td>Otto</td>
            <td>@mdo</td>
          </tr>
          
          <!-- More rows -->
        
        </tbody>
      </table>

      <div class="example">
        ... Example ...
      </div>

      <div class="example">
        ... Example ...
      </div>

      <div class="example">
        ... Example ...
      </div>

      <!-- ...
        Some other elements
        .. -->

    </div>
  </div>
</div>

Is there any specific feature in Bootstrap that can help with achieving a fixed/sticky table header layout?

Answer №1

I previously addressed this issue in detail here. To achieve this effect, you can utilize the CSS property position: sticky;

table thead tr th {
  background-color: white;
  position: sticky;
  top: -1px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<table class="table">
  <thead>
    <tr>
      <th>column1</th>
      <th>column2</th>
      <th>column3</th>
      <th>column4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>td</td>
      <td>td</td>
      <td>td</td>
      <td>td</td>
    </tr>
    [REMAINING TABLE ROWS OMITTED FOR BREVITY]
  </tbody>

</table>

Answer №2

To customize your table appearance, you can apply the following CSS code:

table thead tr:first-child th {
  position: sticky;
  top: 0px;
  background-color: #afc8f0;
}

Answer №3

After reading Mohd Tabish Baig's insight, I realized that delving deeper into the target element was necessary. Instead of simply applying position: sticky to the thead, it needed to be added more specifically to its child elements th's. The solution provided in the following fiddle proved to be very helpful:

.example {
  padding: 5px;
  margin: 5px 0;
  border-radius: 2px;
  background-color: #afc8f0;
  text-align: center;
}

table thead tr th {
  position: sticky;
  top: 0px;
  background: #fff;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col">

      <div class="example">
        ... Example ...
      </div>

      <div class="example">
        ... Example ...
      </div>

      <div class="example">
        ... Example ...
      </div>

      <!-- ...
        Some other elements
        .. -->

      <table class="table table-striped table-hover table-sm">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">First</th>
            <th scope="col">Last</th>
            <th scope="col">Handle</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <th scope="row">1</th>
            <td>Mark</td>
            <td>Otto</td>
            <td>@mdo</td>
          </tr>
          <tr>
            <th scope="row">2</th>
            <td>Jacob</td>
            <td>Thornton</td>
            <td>@fat</td>
          </tr>
          <tr>
            <th scope="row">3</th>
            <td>Larry</td>
            <td>the Bird</td>
            <td>@twitter</td>
          </tr>
          <!-- Repeat rows for brevity -->
        </tbody>
      </table>

      <div class="example">
        ... Example ...
      </div>

      <div class="example">
        ... Example ...
      </div>

      <div class="example">
        ... Example ...
      </div>

      <!-- ...
        Some other elements
        .. -->

    </div>
  </div>
</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

Optimizing window height to 100% on mobile Chrome

My website is designed to adjust based on the size of the browser window, with the first div filling up the entire height using height: 100%. However, I've encountered an issue with certain mobile browsers like Chrome hiding the address bar on devices ...

What are some ways to customize the appearance of a mat-snack-bar template with CSS in Angular Material 7?

I have browsed through various answers, but none of them seem to fully address my specific issue. For instance, this particular answer provides guidance on changing the background color of a snack-bar using CSS, which is helpful. However, attempting to adj ...

Material Design Angular2 Toolbar

I am currently working on designing a toolbar using Material and Angular2. My main challenge is formatting the toolbar in such a way that the search bar appears centered in white, while the "Create Project" button and other buttons are aligned to the right ...

Error Alert: Node.js Detected an Unhandled Promise Rejection on the Login Form

I have created a user registration form in Node.js where I check for duplicate usernames and emails. However, I am facing an error. Can someone please help me out or provide an example? Thank you if (req.body.email_reg && req.body.name_reg & ...

The checkboxes seem to be malfunctioning following an ajax request

I've been attempting to utilize ajax to load data, but for some reason the checkboxes aren't functioning. Below is the HTML I'm trying to load via ajax: <div class="mt-checkbox-list" > <?php foreach($product_offerings as $row){ $c ...

The Gulp task is failing to generate the CSS file

Greetings! I have a task set up in my gulpfile.js as shown below: const gulp = require('gulp'); const sass = require('gulp-sass'); gulp.task('sass', function(){ return gulp.src('sass/*.scss') .pipe(sass()) ...

How can I use Jquery to slide one div over another and replace it in its position?

I am working on creating a unique animation using CSS and jQuery. The animation involves a green box sliding (or growing) over a fixed red box, and then toggling back so that the green box shrinks while the red one reappears. One issue I encountered was u ...

Is Material-UI suitable for use in Java applications?

Is it feasible to integrate Material-UI into a Java application? Currently, I am utilizing Bootstrap and Spring forms for the frontend, while the backend consists of Spring MVC. I would like to implement React for both desktop and mobile interfaces. The ...

Creating a realistic eye blink animation using only CSS on an SVG element

Below is a segment from an SVG file featuring a hyphen character. <path class="right-eye" fill="#000000" d="m556.02527 384.85477l11.03009 -4.0496826l12.407532 33.71103l-11.03009 4.0496826l-12.407532 -33.71103z" fill-rule="nonzero"></path> I a ...

Synchronize the hiding and displaying of elements with a corresponding element

If I had a pair of <div> elements set up like this: <div class="overlay"></div> <!-- More content here --> <div class="popup"></div> Whenever the div.popup element is displayed with display: block, I want the div.overl ...

Trigger JQuery function post CSS styling completion

Upon using $(document).ready(function() {...}, it seems that the function is invoked after the DOM has loaded, but potentially before CSS styles have been completely applied. My goal is to obtain the width of a particular element. Strangely, when attempti ...

Utilizing Bootstrap 3: Achieving Varied Font Sizes within a Row with Bottom Alignment

Just starting out with Bootstrap and looking to create a layout with two columns of text in the same row, where the first column has a larger font size than the second. However, I'm running into an issue where the text in the second column is position ...

What could be causing angular-datatable to not properly fill columns in Bootstrap 4?

I have been attempting to create a responsive table using angular-datatables (for angular 7) and bootstrap 4, but I am encountering issues with the current appearance of the table: Current HTML code: <div class="row"> <d ...

Oops! Smarty encountered a fatal error that wasn't caught

An error occurred while processing the template file "C:\xampp\htdocs\eventos\libs\templates\teste.tpl" on line 9. The error message states: Fatal error: Uncaught exception 'SmartyCompilerException' with message &apo ...

Is there a way to verify that a form field has been completed?

Currently, I am grappling with a method to clear a field if a specific field is filled in and vice versa. This form identifies urgent care locations based on the information provided by users. The required entries include the name of the urgent care facil ...

Creating a sleek and modern 5-column footer design with Bootstrap styling

Apologies if this question seems basic, I am just beginning to explore HTML, CSS, and bootstrap. My goal is to create a footer with five columns using bootstrap. While I have managed to establish the five columns, I have spent hours attempting various met ...

Absence of MVC5 Vanilla Layouts

Creating my first MVC5/Razor application from the ground up, I want to avoid including unnecessary references that cause bloat. In the Views folder, I have separate Home and Shared subfolders. The Home folder contains Index.cshtml, while the Shared folder ...

Locating and clicking a button within a table using Selenium WebDriver with Java, along with an event listener

This is my first question on Stack Overflow and I have not made any progress after a day of research. I am currently experimenting with WebDriver in Netbeans for testing our services. We chose WebDriver because we will need to test file uploads in the fut ...

The Bootstrap image fails to adhere to the size of its parent flex container

I am having trouble positioning an image, heading, and a button on top of another image. The issue arises when viewing the content on small screens as the smaller image fails to resize properly and extends beyond the background of the larger holding imag ...

Error: "$$" not defined in this context

I am currently working on generating a dynamic pie chart programmatically with the intention of transforming it into a reusable React Component. The main idea is to have an interactive pie chart where each slice expands into a full pie when clicked. I came ...