I will demonstrate three methods to achieve your desired outcome,
- css3 Using
flex
(modern browsers only)
- css Using
inline-table
(issue with cell height but functional as a sort-of fallback)
- jquery 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>