Simple Steps for Dynamically Adjusting Table Cells without Disturbing Existing Data

Is there a way to make a table automatically arrange cells in rows of two, adjusting as necessary when adding or removing cells (with one cell in the last row if there is an odd number of total cells)?

For example:

<table>

<tr>
  <td>old1</td> 
  <td>old2</td>
</tr>


<tr>
  <td>old3</td> 
  <td>old4</td>
</tr>

</table>

Could it be transformed into this arrangement?

<table>

<tr>
  <td>NEW</td> 
  <td>old1</td>
</tr>


<tr>
  <td>old2</td> 
  <td>old3</td>
</tr>


<tr>
  <td>old4</td>
</tr>

</table>

Take note of the automatically inserted row.

Answer №1

I will demonstrate three methods to achieve your desired outcome,

  • Using flex (modern browsers only)
  • Using inline-table (issue with cell height but functional as a sort-of fallback)
  • Using standard <table> (All browsers!)

Implementing CSS3's FLEX

.table{
  display: flex;
  flex-wrap: wrap;
}
.cell{
  width:50%;
  background:#ddd;
}
<div class="table">
  <div class="cell">NEW</div>
  <div class="cell">OLD1</div>
  <div class="cell">OLD2</div>
  <div class="cell">OLD3<br>new line</div>
  <div class="cell">OLD4</div>
</div>

Using inline-table (problem with cell height)

display: table;   for the parent element and
display: inline-table for the inner DIVs:

.table{
  display:table;
}
.cell{
  display:inline-table;
  width:50%;     /* With percentage you simulate "how-many-per-Row" */
  background:#ddd;
}
<div class="table">
  <div class="cell">NEW</div>
  <div class="cell">OLD1</div>
  <div class="cell">OLD2</div> <!-- Works but observe this cell height  -->
  <div class="cell">OLD3<br>new line</div> 
  <div class="cell">OLD4</div>
</div>

You can utilize the inline-table method as a backup for older browsers - although it may not produce identical results, it is the best alternative without JavaScript.

Refer to the specification for more information on the display property: https://developer.mozilla.org/en-US/docs/Web/CSS/display


Utilizing <table>, <tr>, and <td> in conjunction with JavaScript (jQuery)

If you prefer to stick with traditional table elements, jQuery can be used to achieve the desired layout.
In this scenario, the approach is slightly more complex (see code-comments):

jQuery(function($){ // DOM is now ready

  var $table = $("table"); // Obtain your table
  var maxRowCells = 2;     // limit of 2 cells per row
  var counter = 0;         // just a placeholder counter

  function prependNewCell(){

    var $newCell = $("<td/>", {html: "NEW"+(++counter)});

    // Is the last row full?
    if($table.find("tr:last td").length == maxRowCells){
      // If true, append a new TR to TABLE for shifting TDs
      $table.append( $("<tr/>") ); 
    }

    // Shift all last TDs to the next row:
    $table.find("tr:not(:last)").each(function(){
    var $tdLast = $(this).find("td").last();
    $(this).next("tr").prepend( $tdLast );
    });

    // Finally. Prepend the new TD element to the first TR
    $table.find("tr").first().prepend( $newCell );

  }

  $("button").on("click", prependNewCell);

});
td{
  width:50%;
  background:#ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>ADD NEW CELL ON TOP</button>

<table>
  <tr>
    <td>OLD1</td>
    <td>OLD2</td>
  </tr>
  <tr>
    <td>OLD3</td>
    <td>OLD4</td>
  </tr>
</table>

Answer №2

td:not([colspan]):empty {
   visibility: hidden;
}

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

Using JavaScript to inject PHP variables into multiple <span> elements

I have been searching for a similar query without any luck. Currently, I am attempting to display the number of Twitter/Facebook/RSS followers within a <span>....</span> in my sidebar. To retrieve the follower counts, I am using some PHP scrip ...

Unable to showcase array JSON values on HTML using ng-model

Utilizing ngTagInput for autocomplete textbox and successfully receiving suggestions. To display the values of data-ng-model (named "list") I am using: {{list}} and it is showing correctly. However, when selecting "list1", the display appears as: [{"lis ...

Tips for making a table have the same width as its child td elements and enabling the table to exceed the width of the viewport

I am facing a challenge with a table that has dynamically changing rows and columns. <table> <tr> <td>column 1</td> <td>column 2</td> <td>column 3</td> </tr> <tr> <td> ...

Despite locating the button, Protractor still encounters difficulties when attempting to click on it

I've been having trouble clicking on a button using Protractor. The issue is that even though the driver can locate the element, it still won't click on it. Any assistance would be greatly appreciated. Thank you in advance. Here is the HTML for ...

Storing multiple text box values into a single application variable in C# - A Comprehensive Guide

[code page="c#"] Hdnano.Value = Application["AccountNum"].ToString(); $(document).ready(function() { $("#ano").on("blur", function() { var accountNum = $('textarea#ano').val(); $("#Hdnano").val(folioNum); }); &l ...

Is there a way to use CSS to make a div expand as much as it can?

I am attempting to accomplish the following; Do you think this is achievable? ...

Is it possible to access the HTML template prior to Outlook applying any additional classes during rendering?

I recently received an email template created in a different platform via Outlook. I am attempting to recreate this email in the Salesforce Marketing Cloud Platform, but I am encountering numerous unnecessary tables, classes set by Outlook (MsoNormal, Ms ...

Choose a text input form field simultaneously?

Is it possible to create a select field that also acts as an input form simultaneously? I need the options in this hybrid field to range from 0.01 to 10.00, while ensuring it always displays 2 decimal places. Curious how I can achieve this functionality ...

Utilizing the power of JavaScript, CSS, and HTML to seamlessly transfer selected items from one webpage to the shopping cart displayed on another page

Due to limitations on using back-end code, I'm seeking advice on how to implement this function. Most tutorials I've come across show the items and shopping cart on the same page. I've heard suggestions about using Jquery.load(), but I&apos ...

Building an expandable vertical dropdown with Bootstrap that opens with a click

My goal is to design a vertical menu that expands when clicked, revealing 3 links for each item. I currently have the following setup: This is the initial layout: After clicking all items: The code I've implemented so far looks like this: <!DOC ...

Detecting Specific Web Browsers on My Website: What's the Best Approach?

My website is experiencing compatibility issues with certain browsers, such as Firefox. I want to display a message when users visit the webpage using an unsupported browser, similar to how http://species-in-pieces.com shows a notification saying "Works ...

Is it possible to access the operating system's native emoji picker directly from a website?

While there are numerous javascript plugins and libraries available for allowing users to select emojis for text inputs, both Windows and Mac operating systems already have their own native emoji pickers accessible via ⊞ Win. or CTRL⌘Space. Is there a ...

Production environment poses a challenge as Rails 4 struggles to locate fonts

Situation: I am facing an issue with my Rails 4.0.0 application deployed using capistrano, where the asset precompilation does not work properly on my production server. Challenge: Despite successfully adding a font and using it with @font-face locally, t ...

Guide to aligning text to the right using the text-muted class

I'm attempting to align the text-muted class to the right side of the page. I've tried floating it right, pulling it right, but nothing seems to be working. <table class="table table-bordered"> <tbody> <tr> < ...

What is the best way to conceal floated elements with overflow in CSS?

How can I ensure that my block container element only displays the content of block elements, cutting off any floated elements that are taller than the parent container? Applying overflow: hidden seemed like a simple solution, but it created a new block f ...

Create an additional column in HTML using Bootstrap styling

I am currently working on a CRUD form (using PHPMyAdmin for the database), developed in HTML, JavaScript, and PHP. The queries are executed using jQuery. I am facing an issue with my code - whenever I add a new column to my table, the formatting gets messe ...

Positioning the footer to sit at the bottom of my webpage, leaving a pleasing margin at the top

One technique I frequently use to ensure my footer stays at the bottom of my page is by utilizing an empty div. Here's how the code looks: <body> <div id="canevas"> <article>My website's content</article> ...

Is there a way to change the domain for all relative URLs on an HTML page to a different one that is not its current domain, including in HTML elements and JavaScript HTTP Requests?

I am dealing with a situation where my page contains "domain relative URLs" like ../file/foo or /file/foo within a href attributes, img src attributes, video, audio, web components, js ajax calls, etc. The issue arises when these URLs need to be relative ...

I am looking to extract specific data from a webpage using Webscraping and page_soup.findAll, but I am unsure of the correct method to do

I'm currently working on a web scraping project and I'm trying to extract the keywords from a webpage. I attempted to use page_soup.findAll() for extraction, but I'm unsure of what to include between the parentheses to get the desired inform ...

Creating unique ID tags using AngularJS

I am struggling with creating an HTML structure that looks like this: <ul> <li id="r1_1">Root node 1 <ul> <li id="child_node_1">Child node 1</li> <li id="child_node_2">Child node 2</ ...