Search code examples
javascriptjqueryhtmlhtml-tabledisplay

How to display multiple html tables in 2 columns


I have an application running on jQuery which fetches some data and creates html tables by appending the newly created tables inside a div element.
The tables are displayed fine, but I would like them to appear next to each other so that the user can see them 2 by 2 and avoid scrolling up and down all the time.

Code Structure:

<div id=example>
 <table id=1>
  <tr>
   <td>..</td><td>..</td>
  </tr>
 <table>
 <table id=2>
  <tr>
   <td>..</td><td>..</td>
  </tr>
  more rows..
 <table>
</div>

Tables have dynamic number of rows and some rows have different number of cells.

The wanted outcome is:

table1 | table2
table3 | table4
table5 | table6
etc.

How can I do that either in html(when constructing the tables) or after with jQuery selectors and filters?


Solution

  • After trying different things, the easiest solution was to use Flexbox.

    My solution was based on Jan Derk's answer from this post.

    Since I only wanted 2 columns I used the float: left/right property on my tables:

    jQuery("table").each(function(index, value) {
    
        if(index%2===0){
    
            jQuery(this).css({"float": "center","width": "45%"});
    
        }else {
    
            jQuery(this).css({"float": "left","width": "45%"});
    
        }
    
    });
    

    and then on the surrounding Div element I assigned these CSS properties:

    jQuery("#div_id").css({"display":"flex","flex-wrap":"wrap", "justify-content": "center"});
    

    This solution is also responsive and resizes dynamically as you resize the window or use a mobile screen.