Uniform dimensions for HTML tables

When creating an HTML document with consecutive tables that need to be formatted the same way, it can be challenging. Browsers will often render columns of one table wider than another simply due to content width.

The typical solution is to hard-code column widths, but this can be problematic as it depends on various factors like font choice and screen width. The user agent is better at deciding layout than we are, so fixing column widths may not be ideal.

One option could be combining the tables into a single table with CSS tricks to hide the separation, but this feels wrong and would make the code messy.

An alternative approach might be treating the two tables as sections of one logical table by using separate <tbody> elements:

<table>
  <thead><tr><th>Name</th><th>Identifier</th></tr></thead>
  <tbody><tr><td>John Smith</td><td>A-64</td></tr></tbody>
  <tbody><tr><td>Xavier Ephraim Bloggs III</td><td>A-434-bcf</td></tr></tbody>
</table>
<p>Some text &hellip;</p>

Are there any CSS/HTML5 tricks available to move the second <tbody> (including its header) after the paragraph?

Answer №1

After much deliberation, I ultimately determined that a CSS/HTML solution was unattainable, but accomplishing the task with JQuery was relatively straightforward.

$( "table.splittable" ).each( function() {
    $(this).find("tr").first().children().each( function() {
        this.setAttribute('width', this.offsetWidth);
    } );

    var hdrs = $(this).find("tr.move-header");
    $(this).find("tr").each( function() {
        var tr = this;
        $( this.className.split(/\s+/) ).each( function() {
            var match = this.match(/^move-to-(.*)$/);
            if (match) { 
                var dest = $('#'+match[1]).get(0);
                if (dest.childNodes.length == 0) {
                    var thead = document.createElement("thead");
                    dest.appendChild(thead);
                    hdrs.each( function() { 
                        thead.appendChild(this.cloneNode(true)); 
                    } );
                    dest.appendChild(document.createElement("tfoot"));
                    dest = dest.appendChild(document.createElement("tbody"));
                }
                else dest = $(dest).find("tbody").get(0);
                dest.appendChild(tr);
            }
        } );
    } );
});

This specific script examines each table with the splittable class, ensuring they are fully rendered in the browser before fixing column widths by adding a width attribute based on optimal browser settings. It then identifies rows with the move-to-<em>something</em> class and relocates them to the table with a corresponding id of <em>something</em>. If the destination table lacks a <thead> element, any rows in the source table with the move-header class are duplicated there.

As a result, my approach involves placing content within a single table and inserting an empty placeholder table where subsequent line(s) should be moved:

<table class="splittable" id="table1">
  <thead><tr class="move-header"><th>Name</th><th>Identifier</th></tr></thead>
  <tbody>
    <tr class="move-to-table1"><td>John Smith</td><td>A-64</td></tr>
    <tr class="move-to-table2"><td>Xavier Ephraim Bloggs III</td><td>A-434-bcf</td></tr>
  </tbody>
</table>

<p>Some text …</p>

<table class="table2"></table>

Once the JavaScript executes, the second table acquires a replica of the header, and the last line is transferred there. Both tables now possess identical column widths.

Admittedly, this method may appear somewhat messy and does not gracefully handle situations where JavaScript is disabled. Nevertheless, it represents the most suitable solution I have devised thus far.

Answer №2

Have you considered enclosing everything in a parent container? This can be used to set the overall width based on its parent or specific device/screen size rules.

By setting column widths as a relative percentage (e.g. 50% for 2 columns, 25% for 4 columns), you can achieve the desired layout.

table { width: 100%; }
td { width: 50%; }

Check out this fiddle for an example: http://jsfiddle.net/5q8Zc/

In response to the debate whether it should be seen as one table or two, my perspective differs. If each section needs a distinct header and contains unique content, I would consider them as separate tables. However, without viewing the full page, it may be challenging to make a definitive judgement.

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

Can someone explain to me how I can customize the background of a bootstrap container?

Currently, I am working on an EJS login project and I have created a style.css file with the following code: [theme="bloodRed"] { background-color: #ff2424; color: #e571e1; accent-color: #00ff00; } In my register.ejs ...

Utilizing CSS to incorporate a background image into HTML code

Is it feasible to utilize pure HTML for the background-image property? Consider the following scenario: The original: background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height=&apo ...

Creating a centered and beautifully styled picture with a specific maximum size using React

I recently completed the development of a new website, which can be viewed at Upon inspection of the website, it is evident that the photo is not centered and appears too large on mobile phones. Despite my efforts to align it using various methods outline ...

I am having trouble aligning the unordered list in the center

My struggle lies in centering the ul element which serves as a menu. Despite trying various CSS properties such as margin: 0 auto;, text-align: center;, and adjusting the margin value, I am unable to achieve the desired result. This is the CSS code I have ...

What is the best way to adjust the height of a dropdown box in an angular application?

Is there a way to change the height of the scroll view? It seems too long for my liking, any advice? I attempted to adjust it using css but unfortunately, it didn't work out. The scroll view appears excessively lengthy as shown in the image below. h ...

Experience the combined power of addthis, isotope, and nicescroll - all in a single

I am utilizing a WordPress template that includes a set of share buttons from AddThis. <ul class="addthis extra"> <li class="addthis-hold"> <div class="addthis_toolbox" addthis:url="<?php the_permalink( ...

employ the value of one array in a different array

Currently, I am working with an array (const second) that is being used in a select element to display numbers as dropdown options {option.target}. My question is: Is there a way to check within this map (that I'm using) if the 'target' from ...

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 ...

Once I incorporated Bootstrap into my project, I noticed a noticeable white space between the div elements

Welcome to My Code Playground I was sailing smoothly with my project until I decided to include Bootstrap. Seems like there's something missing in the details, so here I am reaching out. If you spot the issue, please feel free to correct my code. &l ...

Icon alignment to wrapped text width has been successfully achieved with the implementation of Flexbox onto a single

I am facing an issue with text wrapping within a flexbox. I want the width of the flex item to always match the length of the wrapped text so that an icon placed next to the item stays adjacent to the text. However, due to text wrapping, there is a gap bet ...

Why is a div nested inside an overflow: hidden; div not expanding to the full width of its content?

.container { white-space: nowrap; overflow: hidden; } .inner { width: 100%; } .list-item { display: 'inline-block', boxSizing: 'border-box', border: '3px solid black' } import React, { Component } from 're ...

Google Chrome Back Button not saving radio button selections

We have noticed an issue with Google Chrome wherein the back button does not retain radio box selections when submitting a form that contains all radio boxes. This seems to be specific to Chrome and is not observed in other browsers like IE and Firefox. B ...

Issues encountered while sending HTML Form data to MySQL with Node JS

I have been experimenting with a basic html form to mysql using nodejs, but unfortunately it is not functioning as expected. The HTML file is named index.html and the Node.js file is called test.js. Below you can find my code: My HTML <!DOCTYPE html&g ...

Is the div height set to 100% until the content surpasses the height of the browser window

Is there a method to make a div fill 100% of the available page height, until it contains enough content to require a scrollbar? // For example, if the browser height is 600px: <div> // Initially empty, so it will be 600px tall. </div> . ...

Struggling to include a CSS link to the file, but encountering failure due to a space within the path

The path to the stylesheet is located at C:\Users\abc xyz\Downloads\link-to-a-stylesheet\css. The editor highlights the section after abc in green, but unfortunately, it is not functioning as expected. ...

The lower section of the scrollbar is not visible

Whenever the vertical scroll bar appears on my website, the bottom half of it seems to be missing. For a live demonstration, you can visit the site HERE (navigate to the "FURTHER READING" tab). HTML: <!DOCTYPE html> <html lang="en"> <h ...

Tips for organizing a Bootstrap 4 menu overflowing with elements

I'm struggling to figure out how to organize a Bootstrap 4 menu with numerous links. Currently, when I include too many links, the navbar disregards the container and expands its width beyond the container. Here is an image for better clarification: ...

Issue with jQuery incorrectly calculating height post-refresh

I am currently utilizing jQuery to vertically center various elements on a webpage. Due to lack of support in older versions of IE, I cannot use the table-cell CSS statement. Therefore, I am using jQuery to calculate half of the height and then position it ...

Struggling to properly center the footer on my Django template

I'm currently facing an issue when attempting to align my footer in the center of my Django template. The specific class for the footer is Pagination. Base HTML: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict ...

Create a dynamic calendar by integrating dates with Javascript and an HTML table

Recently, I decided to delve into web design again and embark on a challenging project for my father's baseball business. The main task at hand is creating a detailed calendar using HTML tables. After spending a considerable amount of time perfecting ...