Linking the width of Table1's th with the width of Table2's td

I am working with two tables - table1 contains only th tags and table2 contains only td tags. Despite the unconventional setup, it is due to limitations in the application. Each TH in table1 acts as a sorting button corresponding to the TD in table2.

While the full width of both tables is the same, the TH's and TD's have different widths causing misalignment. I need to find a solution to link each individual TH to the width of the TD below it. The challenge lies in the dynamic nature of the TH sorting buttons, as users can add or remove them, requiring the widths to adjust accordingly. Finding a seamless linking mechanism is proving difficult. Any suggestions?

For example:

<table id="table1">
 <thead>
 <th>Sort 1</th>
 <th>Sort 2</th>
 <th>Sort 3</th>
 <th>Sort 4</th>
 </thead>
</table>
<table id="table2">
 <thead>
 <td>Data 1</td>
 <td>Data 2</td>
 <td>Data 3</td>
 <td>Data 4</td>
 </thead>
</table>

I have created a basic Fiddle illustrating the issue. The last few td's get squeezed into the "Sorts7" column. My goal is for the TH and corresponding TD to maintain equal width, regardless of added or removed columns.

View the Fiddle

Thank you for your assistance.

Edit: It is necessary for the two tables to remain separate, despite the inconvenience.

Answer №1

Although I may not be a fan of this solution, it does get the job done...

One way to tackle this is by utilizing jQuery in order to fetch the widths of the lower columns and then applying them to the upper columns - here's how you can do it:

$('#top1').css({"width":$("#bottom1").width()});
$('#top2').css({"width":$("#bottom2").width()});
$('#top3').css({"width":$("#bottom3").width()});
$('#top4').css({"width":$("#bottom4").width()});
table, th, td {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="table1">
 <thead>
 <th id="top1">Sorts 1</th>
 <th id="top2">Sorts 2</th>
 <th id="top3">Sorts 3</th>
 <th id="top4">Sorts 4</th>
 </thead>
</table>
<br> <!-- To demonstrate that they are separate -->
<table id="table2">
 <tr>
 <td id="bottom1">Sort 1</td>
 <td id="bottom2">Sort 2 With Longer Content</td>
 <td id="bottom3">Sort 3</td>
 <td id="bottom4">Sort 4</td>
 </tr>
 <tr>
 <td id="bottom1">Sort 1</td>
 <td id="bottom2">Sort 2</td>
 <td id="bottom3">Sort 3 With Longer Content</td>
 <td id="bottom4">Sort 4</td>
 </tr>
</table>

Fingers crossed that you're not dealing with an extensive array of columns!

Answer №2

It is possible to utilize one class for both table headers and table data cells.

Answer №3

Does this solution meet your requirements?

I opted for jQuery to keep things simple:

$( "#table2 tr td" ).each(function( index ) {
    $('#table1 th').eq(index).css('width',$(this).width()+'px');
});

Check out the live demonstration: https://jsfiddle.net/6u1dyL55/10/

The approach involves obtaining the widths of the table cells and applying them to the respective table headers in the first table (using indexes as they align).

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 reloading iframe and redirecting parent origin

On the same domain, I need to navigate through a login form using code and redirect to another page. The login process involves configuring settings across internal servers. To achieve this, I have created a page with an embedded iFrame: <iframe id=" ...

What is the best way to compare my filter search input with my regular expression?

My image gallery has a search field where I can type #cat to filter through the tags of my images extracted from a JSON file using a separate variable. However, the Regex I'm using searches for tags that partially contain the word, rather than the sp ...

Do GPU-intensive animations get impacted by the CPU's load?

I have set up a special compositing layer for a div with the following unique styles: div { position: absolute; height: 50px; width: 50px; background: #900; top: 100px; left: 200px; will-change: transform; transform: translateZ(0); } Afte ...

After releasing the project, CSS fails to load properly

After creating a website in Visual Studio and deploying it in IIS, I encountered an issue where the CSS was not loading when trying to access the site. I followed some advice to update the path of the CSS file location, but that didn't resolve the pro ...

Insert a new store into an existing IndexedDB database that is already open

After opening and passing the onupgradeneeded event in IndexedDB, is there a way to create a new store? My attempted code: var store = db.createObjectStore('blah', {keyPath: "id", autoIncrement:true}); This resulted in the following error mess ...

Steps for connecting a div to a collapsible navigation bar

I have a website with a collapsible navbar at the top for small screens. I want to add a red circle positioned on the right side of the navbar. Something like this: view image here The circle is not a button and should be centered on the border of the navb ...

Querying MongoDB with Mongoose to find objects in an array based on a specific date stored

I am currently working on constructing a mongoose query to retrieve records that match a specific date. It seems like the query is functioning properly, but I'm not getting any results displayed because the date stored in my array of objects is a stri ...

Ways to display information from the server on the client's website

I have received the following dataset from the server and stored it in the 'res' variable on the client side: 0: {date: "2014-12-02T00:00:00", close: 106.9064, buySell: "Sell"} 1: {date: "2014-12-03T00:00:00", close: 108.1188, buySell: "Sell"} 2 ...

Is it possible for a scope object to access its own properties using the keyword "this"?

Can anyone help me figure out how to calculate the total fees in this example? $scope.fees = { basic: 1, premium: 2, total: this.basic + this.premium } I'm getting an error that says this is undefined. Is there a better way to do this wi ...

Utilizing Express Session with Vue CLI in a Node.js Environment

Developing a nodejs backend for my Vue application has brought up a challenge regarding user sessions and database operations. I initially tried using express-session, but the sessions appeared as undefined in subsequent requests. How can I address this is ...

What is causing the fs.readFile function to give back undefined instead of the expected result?

/** * A function to determine the cost of an employee from a specific data file * @param {string} filePath - the path to the employee data file * @returns {{name: string, cost: number}} - the name and cost of the employee */ function calculateEmployee ...

JavaScript Object Notation, asynchronous JavaScript and XML, and Active Server Pages

In my client-side file, there is an ajax call within jQuery that sends JSON data to a WebMethod on the server-side. The code snippet below demonstrates how it can be achieved: Server-side WebMethod (C#) [System.Web.Services.WebMethod] public static strin ...

Unraveling the Inner Workings of Promise Chaining

Currently, I am diving into the world of promise chaining and have encountered a question. Let's take a look at this example with a promise chain: const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve(" ...

Validating groups of fields using Angular fieldsets

AngularJS validation is working well with ng-required. However, I am interested in checking if all the form elements within my fieldset are valid. <form> <fieldset> <legend> Part one <img src="/co ...

When attempting to send coordinates to the Polyline component in React Native, an error is encountered stating that NSNumber cannot be converted to

Trying to pass coordinates from BackgroundGeolocation.getLocations() is causing an issue. Upon passing the coordinates, I encounter the following error message: JSON value '-122.02235491' of type NSNumber cannot be converted to NSDictionary I ha ...

What could be the reason for the absence of a second alert appearing?

I have a small application that validates email addresses for the correct elements, but it's not displaying the confirmation message. $(document).ready(function(){ $("#sendButton").click(function(){ var name = $("#name").val(); ...

What is the best way to establish the starting property state for CSS Animation?

I'm looking to create an animation that involves the following steps: Initial: elementA starts with opacity set at 0; When hovering over containerA, which contains elementA: elementA transitions from position (-5px, 5px) to (0px, 0px); elementA ch ...

Choosing the Right JS Framework for an iPad HTML Prototype

Is there a quality Javascript framework available specifically for creating iPad prototypes? I've been searching but haven't found anything helpful yet. Cheers, Stefan ...

Avoiding using the symbols < and > in JavaScript code before assigning it to InnerHtml

I am dynamically adding JavaScript code to a script tag by setting the InnerHtml property of the HtmlNode. scriptNode.InnerHtml = new_script; The issue arises when my JavaScript code contains less than < and/or greater than > characters, which dist ...

Struggling with the Communication of Data between React Native and a React Application Rendered in WebView

I am currently working on a project that involves sending gyroscope data from a React Native app to a React app embedded within a WebView. Unfortunately, I have been encountering challenges in transmitting this data successfully. To simplify things, I woul ...