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

Tips for transferring a jQuery array to PHP

I am encountering an issue when trying to send a jQuery array to PHP. Initially, I have one form in HTML and upon clicking 'add', I end up with two forms. Afterwards, I input data into the form which is then stored in a jQuery array. However, I a ...

What is the best way to adjust the width of a column to perfectly fit its contents when using IE9 compatibility mode?

Within my HTML code, I've included the table displayed below. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <style type="text/css"> table, td, tr, th{ border:1px; } .onepx{ ...

Concealing subcategories within a responsive menu using jQuery

My website's responsive menu changes based on screen resolution, but I encountered an issue. On mobile viewports, the sub items in the menu are displayed by default. I want them to only appear when the parent item is clicked. Currently, clicking the p ...

Centered image

I am working on a website and struggling to center the image on all screen sizes. I attempted the following code:- <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript" lang ...

What is the difference between a CSS background image and a default background?

I am faced with a challenge concerning a div element that has both a background color and an image with a transparent background. My objective is to have the default background color of the div be white, while having a different color as the background fo ...

Step-by-step guide: Creating a captivating triangular shape on the current tab

I am trying to implement a dynamic tab using Bootstrap where clicking on a tab will display a thicker black underline, like in this image: https://i.stack.imgur.com/h48GB.png To achieve the black line effect, I have added the following code: .nav-tabs.n ...

Tips on fixing image movement when scrolling and switching resolutions

I am currently working on developing my HTML/CSS portfolio. However, I am facing an issue where the images on the site move around whenever the scroll level or resolution size is changed. I want the images to remain in their respective blocks, displayed at ...

Changing images based on different triggers - HTML Markup with jQuery Carousel

I have a website where I'm using a plugin called CarouFredSel, available at Most of the time, it works perfectly fine. However, there are some images that cause the markup to break. I've tried troubleshooting the issue but haven't been able ...

How to read a text file in JavaScript line by line

Coding Challenge: <script src="../scripts/jquery-3.1.0.min.js"></script> <script> $(document).ready(function(){ $('#test').click(function(){ var txtFile = '../data/mail.txt'; var file ...

What is the best way to ensure that multiple bootstrap buttons in a row have the same width?

Could you help me figure out how to make the <div id="full"> element take up the full width of its parent container, while also ensuring that the 3 buttons inside share this width and have equal sizes with gaps between them? https://i.stac ...

Incorporate web control's stylesheet into page with UpdatePanel registration

What is the most effective way to register a stylesheet only once on a page using a custom web control? Keep in mind that the page utilizes an UpdatePanel for asynchronous calls. I attempted placing the <link> tag in ScriptManager.RegisterClientScrip ...

Unsure how to proceed with resolving lint errors that are causing changes in the code

Updated. I made changes to the code but I am still encountering the following error: Error Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. It is recom ...

Exploring jQuery Efficiency: Comparing CSS and Animation Techniques

I am trying to steer clear of using the animation property because it tends to be slower compared to CSS3 animations. My query is whether utilizing the css method is faster than the animation property, but still slower than a direct CSS3 animation with tr ...

What is the best way to hide the button when a user is viewing their own profile in an Angular application?

Each user has their own profile on the platform. A unique feature allows users to send messages by clicking a button when viewing other profiles. However, an issue arises where this messaging button also appears on a user's own profile. Is there a way ...

The HTML page is not responsive to the screen size of the mobile device

Check out my HTML code: <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Test</title> <style type= ...

What is the best way to add an image to a SVG placeholder?

This is all unfamiliar territory for me. I am experimenting with the Bootstrap template named "Carousel" as my starting point, utilizing Bootstrap 5.3.2. Here is the link to the Carousel example Everything seems fine so far. However, I am struggling to l ...

Displaying truncated title text

Would it be feasible to display clipped text (overflow: hidden) in a way that is fully readable when hovered over? An attempt like this: div:hover { overflow: visible; background-color: yellow; } results in the text overlapping, making it impossible ...

`Turn nested JSON into a formatted list using jquery`

I am currently facing two challenges: I am having trouble with the HTML structure, as shown in the image below Current HTML structure: https://i.stack.imgur.com/GH46J.png Desired HTML structure: https://i.stack.imgur.com/Dq3Gn.png How can I create d ...

Should I use a single CSS file or separate CSS files for each page?

As I construct my website pages, I often ponder whether it's best to utilize separate stylesheets for each page or to have one comprehensive stylesheet for the entire site. In terms of loading efficiency, wouldn't having individual files be more ...

Guide on changing the CSS of MUI parent components to set the display of buttons to 'block' in React

I'm facing a challenge with my modal design for mobile view. I need the buttons to display in a stacked format, one above the other, taking up the full width of the modal. I've been exploring ways to override the existing CSS within the component ...