In HTML, adjust column widths for multiple tables according to the widest column present in any of them

With Python, I am creating an HTML page that contains multiple tables with the same number of columns, all holding the same type of data. While the generated page is functional, I would like to improve readability by ensuring that all tables have the same width. Currently, each table either has a different width or experiences text overflow in the columns.

To address this issue, I have added custom CSS styles to set fixed widths for each column in the tables. However, manually setting these widths for each column is not a scalable solution.

I am now looking for a dynamic solution to ensure that all tables have consistent column widths based on the widest column found across any of the tables. This would involve setting the width of columns like "Test Case Name" and "Owner" to match the widest instance of those columns among all tables.

If you look at the provided example, you will notice discrepancies in the widths of the tables and their respective columns. My objective is to create a script, potentially using JavaScript, that calculates the appropriate column widths dynamically instead of statically defining them in the CSS.

I have attempted to implement some solutions found online but have not achieved the desired result due to the complexity of my table structure. Any assistance or guidance on how to achieve this dynamic column sizing would be greatly appreciated. Thank you.

Answer №1

I utilized jQuery to adjust the column widths of two tables.


$('#table2 th').each(function(idx) {
  var w1 = $('#table1 thead tr').children("th:eq(" + idx + ")").width();
  var w2 = $(this).width();
  if (w1 > w2)
    $(this).css("min-width", w1 + "px");
  else if (w2 > w1)
    $('#table1 thead tr').children("th:eq(" + idx + ")").css("min-width", w2 + "px");
});
table {
  table-layout: fixed;
  margin-bottom: 2em;
  border-bottom: 1px solid #ddd;
  border-right: 1px solid #ddd;
  border-spacing: 0;
  border-collapse: collapse;
}

table th {
  padding: .2em 1em;
  background-color: #eee;
  border-top: 1px solid #ddd;
  border-left: 1px solid #ddd;
}

table td {
  padding: .2em 1em;
  border-top: 1px solid #ddd;
  border-left: 1px solid #ddd;
  vertical-align: top;
}

table th:nth-child(1) {
  min-width: 100px;
}

table th:nth-child(2) {
  min-width: 250px;
}

table th:nth-child(3) {
  min-width: 100px;
}

table th:nth-child(4) {
  min-width: 100px;
}

table th:nth-child(5) {
  min-width: 250px;
}

table th:nth-child(6) {
  min-width: 100px;
}

table th:nth-child(7) {
  min-width: 100px;
}

table th:nth-child(8) {
  min-width: 100px;
}

table th:nth-child(9) {
  min-width: 100px;
}

table th:nth-child(10) {
  min-width: 100px;
}

table td {
  text-align: left;
  word-wrap: break-word;
}

code {
  white-space: pre-wrap;
}

span.smallcaps {
  font-variant: small-caps;
}

span.underline {
  text-decoration: underline;
}

div.column {
  display: inline-block;
  vertical-align: top;
  width: 50%;
}

div.hanging-indent {
  margin-left: 1.5em;
  text-indent: -1.5em;
}

ul.task-list {
  list-style: none;
}
<h1 id="suite-test-cases">Suite test cases</h1>
<table id="table1">
  <thead>
    <tr class="header">
      <th>Test Case</th>
      <th>Test Case<br>Name</th>
      <th>Owner</th>
      <th>State</th>
      <th>Test Case<br>Description</th>
      <th>Design</th>
      <th>Preconditions</th>
      <th>Depends on</th>
      <th>Dependencies</th>
      <th>Comment</th>
    </tr>
  </thead>
  <tbody>
    <tr class="odd">
      <td>ID.PFIBD1</td>
      <td>Fill in billing details</td>
      <td></td>
      <td>Done</td>
      <td>Log into application with user without paid subscription and create new subscription</td>
      <td>1. Log In (more in ID.CCU1)<br>2. Assert visibility of non active subscription pop-up<br>3. Enter ...
      <td></td>
      <td>ID.CCU1</td>
      <td>1. ID.PUBI1<br>2. ID.PDBI1<br>3. ID.PFIBD4</td>
      <td></td>
    </tr>
  </tbody>
</table>
<h1 id="suite-test-cases-1">Suite test cases</h1>
<table id="table2">
  <thead>
    <tr class="header">
      <th>Test Case</th>
      <th>Test Case<br>Name</th>
      <th>Owner</th>
      <th>State</th>
      <th>Test Case<br>Description</th>
      <th>Design</th>
      <th>Preconditions</th>
      <th>Depends on</th>
      <th>Dependencies</th>
      <th>Comment</th>
    </tr>
  </thead>
  <tbody>
    <tr class="odd">
      <td>ID.CCU2</td>
      <td>Create User</td>
      <td></td>
      <td>WIP</td>
      <td>Create single unique user</td>
      <td>1. Goto settings screen<br>2. Wait until all elements visible<br>3. Enter newly generated email into the Create User field<br>4. Wait for aside menu to be visible<br>5. Fill in all the&... 
      <td></td>
      <td>ID.CCU1</td>
      <td>1. ID.DDU1<br>2. ID.UUU1<br>3. ID.UUU2</td>
      <td></td>
    </tr>
  </tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

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 process for updating a database using a web browser in Django?

I've completed the ADDING stage successfully, but I'm facing a roadblock in the EDITING stage. The objective is to empower the admin to modify the specifics of a specific member via the browser. Any suggestions? While I've made progress with ...

Merge two JavaScript functions

I've been attempting to merge two if functions together but I keep encountering errors. Despite trying different methods, I have not been successful in combining them. My goal is to check if the body has a specific class and if it does, I want to unc ...

Explaining the jQuery $.post method

After a thorough search, I finally discovered the importance of adding return false; at the end of my JQuery code for posting data. Without it, my code wasn't functioning as expected. As a beginner in JQuery, I would appreciate some insights into the ...

Progress Circles on Canvas in FireFox

Currently, I am experimenting with this codepen demo that utilizes canvas to generate progress circles: The functionality functions perfectly in Chrome and Safari; however, it only displays black circles in FireFox. My knowledge of canvas is limited, so I ...

Inserting a new key-value pair into each object within an array

I have a collection of items that I need to add a specific key to in AngularJS using $scope. The following code shows the initial objects: $scope.Items = [ {name:'Jani',country:'Norway'}, {name:'Hege',country:'Sw ...

Can you nest an if statement within another if statement within a return statement?

Is it feasible to include an if statement inside another if statement within a return function? I understand the standard syntax like: return ( <div> { myVar ? <Component/> : <AnotherComponent/> } </div> ...

HTML block failing to implement Bootstrap styling

I am struggling to integrate Bootstrap into Drupal. I have used the 'row' class for the contact ID and added col-sm-12 for title and desc, but it is not working as expected. The width of the container seems off. Also, the accordion.js script work ...

Tips for stopping Vue.js automatic merging of CSS classes

Recently, I embarked on my journey with Vue.js and have been thoroughly enjoying the experience. However, I've stumbled upon a challenge that has me stumped. Despite searching high and low and studying the documentation, I haven't found a solutio ...

"Upon loading the page, I encounter JavaScript errors related to Angular's ngOnInit function. However, despite these errors,

I have a page in angular where I am loading data in the ngOnInit function. The data loads correctly and is displayed on the page, everything seems to be working fine. However, I am encountering numerous javascript errors in the console stating cannot read ...

Tips for updating state in response to changes in props

I am working on a project where I have a Parent component that renders a large form. The Parent component has child components Child1 - Child4, which are responsible for rendering input fields. Whenever the props of the Parent component change, I need to ...

Eliminate Tracking Parameters from URL

I rely on UTM parameters to monitor incoming links within Google Analytics. Consider a scenario where my URL appears as follows https://www.example.com/store?utm_source=newsletter&utm_medium=email&utm_campaign=spring_sale I am looking to streaml ...

I'm looking for a way to track the progress of an ajax call. Specifically, I want to know how I

I am currently working on an AJAX call that executes a lengthy PHP script producing 20 different results. I aim to display the progress of each step within the script, such as 1/20 complete, 2/20 complete, 3/20 complete. Last updated on 29-12-2015 at 03:1 ...

Accessing Row Data from a Material Table using a Button Click, Not through Row Selection

My React component features a material table view, shown here: https://i.stack.imgur.com/OUVOD.png Whenever the delete icon is clicked in the table, I want to access the rowdata associated with that particular row. However, all I am able to retrieve is ...

When an input value changes in jQuery, the script attempts to locate the parent element and then find the next input. However, in some cases, the value returned

I am currently attempting to retrieve the nearest input field within the same or different class that is located in the subsequent row div section. Unfortunately, I am receiving an 'undefined' response and unable to acquire the desired informatio ...

Place the image on the canvas and adjust its shape to a circle

Here is the code I used to insert an image into a canvas: <script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script> <button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Imag ...

Anomaly observed in the deconstruction of Material UI table components

Utilizing the table component from the Material UI react components library, I encountered a need to incorporate custom behavior into the TableRow. To achieve this, my approach involved breaking down the table and planning to encapsulate it within my own ...

I have been working on creating a hangman game, and although I have figured out the logic behind it, I am experiencing an issue where it is not functioning properly. After inspect

I am currently working on a basic hangman game using only HTML and JavaScript. I have the logic in place, but it doesn't seem to be functioning correctly. When I inspected the element, it showed an error saying 'undefined toUppercase.' As a ...

Tips for initiating and terminating the evaluation of a condition at regular intervals using JavaScript

I'm currently working on a JavaScript application where I need to achieve the following: Periodically check every 5 seconds to see if there is an element with the 'video' tag on the page. Once an element with the 'video' tag ...

Guide to using the Firefox WebExtensions API to make AJAX requests to the website of the current tab

I am trying to develop a web extension that will initiate an AJAX call to the website currently being viewed by the user. The specific endpoint I need to access on this website is located at /foo/bar?query=. Am I facing any obstacles in using either the f ...

Utilize jQuery method in HTML to perform parsing operation

Is it possible to invoke my jQuery function from within my HTML code? Here is the code snippet: HTML section: <td style="text-align:left;" align="left" > <div id="bulletin-timestamp" > doTimeStamp(${bulletinTimeStamp[status.index ...