Keep table header stationary while accommodating varying column widths

I have come across various solutions for freezing a table header row, such as creating a separate table containing only the header and hiding the header of the main table. However, these solutions are limited to cases where column widths are predetermined. I am looking for a solution where the columns in my table adjust according to their content. Furthermore, I prefer the table to have a responsive design without a fixed height so that it can be used on different devices while utilizing all available space, excluding a reserved space for a header.

Answer №1

In this particular case, the <tbody> functions as the viewport, requiring the rows to have display: table in order to manually set their widths.


To address this issue, I've implemented some JavaScript code that clones and appends the top rows with the most content as hidden rows within the <thead>. Additionally, I have adjusted the CSS for better styling. However, please note that the layout may still break if the content of <th> is longer than that of <td>.

$(function() {

var $table = $('table');

var $body = $table.find('tbody');
var rowTexts = $body.find('tr').map(function() {
  return $(this).text().trim();
}).toArray().sort(function(a, b) {
  return (a.length > b.length) ? -1 : (a.length < b.length) ? 1 : 0;
});

if (rowTexts.length > 5) {
  rowTexts = rowTexts.slice(0, 5);
}

var $head = $table.find('thead');
rowTexts.forEach(function(text) {
  var $hiddenRow = $body.find('tr:contains(' + text + ')').clone().addClass('hidden');
  $head.append($hiddenRow);
});


});
body {
height: 100%;
margin: 0;
padding: 0;
}
table {
border-collapse: collapse;
text-align: left;
margin-top: 44px;
width: 100%;
}
td,
th {
border-bottom: 1px solid black;
height: 44px;
line-height: 44px;
padding: 0 1em;
}
tr.hidden td {
border: 0;
height: 0;
line-height: 0;
overflow: hidden;
}
thead {
display: table;
position: fixed;
top: 0;
width: 100%;
}
thead tr:not(.hidden) {
background: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Key</th>
      <th>Value</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Key that's longer than usual</td>
      <td>Value</td>
    </tr>
    <tr>
      <td>Key</td>
      <td>Value that's longer than usual</td>
    </tr>
    <tr>
      <td>Key</td>
      <td>Value</td>
    </tr>
    <tr>
      <td>Key</td>
      <td>Value</td>
    </tr>
    <tr>
      <td>Key</td>
      <td>Value</td>
    </tr>
    <tr>
      <td>Key</td>
      <td>Value</td>
    </tr>
    <tr>
      <td>Key</td>
      <td>Value</td>
    </tr>
    <tr>
      <td>Key</td>
      <td>Value</td>
    </tr>
    <tr>
      <td>Key</td>
      <td>Value</td>
    </tr>
    <tr>
      <td>Key</td>
      <td>Value</td>
    </tr>
    <tr>
      <td>Key</td>
      <td>Value</td>
        </tr>
  </tbody>
</table>

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

Issue with the Z-Index property not functioning as expected on unordered lists within a dropdown menu

I have a dropdown menu that opens to the left, but it is displaying underneath the content. I attempted adjusting the z-index of the content to 1 and the dropdown to 2, however, this did not resolve the issue. Here is a sample in jsFiddle: https://jsfiddl ...

Is there a way to update a PHP include file without needing to refresh the page?

I've been learning as I go, so some of my questions may seem basic or beyond my current knowledge level. However, I find that peer explanations, examples, and advice are the most effective way for me to learn. Thank you in advance for your help. Usin ...

The option to "open in new tab" is absent from the right-click menu when clicking a link on a website

Why does the option to open a link in a new tab not appear when using JavaScript or jQuery, but it works with an anchor tag? I have tried using window.location and window.open, as well as adding the onclick attribute to a div, but the option still doesn&ap ...

Interactive preview of PDFs with pdf.js adaptation

How can I update my PDF preview when resizing the window? Currently, the canvas resizes but the PDF preview remains the same size. I am struggling to find a solution for this. var myState = { pdf: null, currentPage: 1, zoom ...

How can we avoid re-rendering the same component repeatedly when using React Router v6?

As a beginner in react, I'm facing an issue with preventing components from re-rendering when navigating to a different page. Specifically, I want to display only text on my Signup and Login pages, but the Navbar keeps re-rendering every time I switch ...

What could be the reason for the inconsistent behavior of onClick, causing it to occasionally fail to display the associated

I just started using typescript 2 days ago, mainly to create a custom component for my streamlit app. I've made a navigation bar with a tab that can be clicked on the sidebar, but it's displaying some erratic behavior. Sometimes when I click on t ...

When submitting a form with a contenteditable div and text box using JQuery, the POST request is not

I developed a website that allows users to edit and format text, then save it onto the server. Utilizing jquery to send the data to a PHP page for saving, I encountered an issue where the site fails to send the file name along with the formatted text to PH ...

What could be causing certain link titles to appear outside of my <a> tags?

Check out this jsbin link to see the issue I am facing. I noticed that some of my link titles are appearing outside the anchor tags. Initially, I thought it was because some titles were enclosed in double quotes. I tried creating a function to fix this, b ...

What is the best way to delete the pipe separator from the initial item in a list on the line?

I have a list of items separated by pipes that spans multiple lines. I am looking to use jQuery to remove the pipe separator for the first item on each line. Example: Red | Green | Blue Purple | Black | White Violet | Yellow | Magenta Here is the code ...

Enter the Kannada language into the HTML text box or input field

My html form consists of about 15 - 20 input and textarea fields. As a user, how can I enter information in Kannda or any other local language? https://i.stack.imgur.com/60PVT.png ...

Change the color of the text in a shiny dashboard

While exploring shiny dashboard, I came across this link that explains how to modify colors in the sidebar and header. However, I'm struggling to change the font color for sidebar items. The default white font color becomes unreadable when using light ...

How long does jQuery animation last until completion?

Within my project, I am utilizing the animationComplete function from the jQuery mobile library. You can find this function at The animation in my project involves a sequence of objects with various tasks to be executed at each point of the animation. The ...

What is the best way to position a popup div in CSS?

Currently, I am in the process of developing a website that displays DVD details when hovering over an image, similar to what is shown in picture 1. However, I've encountered an issue where the content gets cut off for DVDs located on the right side o ...

The way images appear can vary between desktop and mobile devices

I am in the process of creating a photography website with a simple goal of displaying images down the page one after another. However, I am encountering issues with uniform display across various desktop and mobile platforms. The site appears perfect on i ...

Tips for sending data through AJAX before the browser is about to close

My issue is with a javascript function that I've called on the html unload event. It seems to be working fine in Google Chrome, but for some reason it's not functioning properly in Firefox and IE. <script> function fun() { ...

The JQuery duplication process did not function as anticipated

This question builds on a previous one related to jQuery cloning and incrementing IDs. The issue is that when adding new elements, the IDs are not being generated in the correct sequence. For example, if the initial ID is expy-1, clicking "add more" should ...

JavaScript condensed into a single table cell rather than occupying an entire webpage

Hey there, I have a simple question that I can't seem to find the answer to anywhere. I'm working on a JavaScript function that pulls data from my database and I want it to display in one cell of a table instead of outputting to the entire page. ...

Loss of styling is observed with jQuery's html() function

Here is the HTML code I am working with: <div class="myList"> <select> <option value="1">Item1</option> <option value="2">Item2</option> </select> </div> Everything looks great in terms of CS ...

Shade of a row within a PHP table

I have a table that is populated with data from a database. Is there a way for me to dynamically change the color of a row based on certain conditions from a JSON file? For example, if the temperature exceeds a set minimum value, I want to highlight the ro ...

What is the best method for eliminating the gap between div elements in CSS?

I am in the process of creating a simple website to brush up on my basic HTML and CSS skills. Utilizing Dreamweaver CS6, I aim to master every aspect of web design the correct way. While exploring how to position div elements, specifically using margins fo ...