JSFiddle - React, Tailwind, and code Playground
HTML
<button id="add">add</button><button id="remove">remove</button>
<div class="products">
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
</div>
CSS
.product {
width:150px;
height:150px;
background-color:blue;
margin:10px;
float:left;
}
.products {
margin: 0 auto;
}
JavaScript
function isInt(n) {
return +n === n && !(n % 1);
}
function format(val) {
var decimal = val.toString().substr(val.toString().indexOf(".") + 1, 1)
if ((val <= 4 || (decimal >= 6 || isInt(val))) && $('.product').outerWidth(true) * val < $('body').width() ) {
return true;
} else {
return false;
}
}
function recalculate() {
for (var i = 1; i < 6; i++) {
if (format($('.product').length/i)) {
$('.products').width($('.product').outerWidth(true) * $('.product').length/i);
break;
}
}
}
$(window).resize(function() {
recalculate();
});
$(function() {
recalculate();
$( "#add" ).click(function() {
$('.products').append('<div class="product"></div>');
recalculate();
});
$( "#remove" ).click(function() {
$('.products div:last-child').remove();
recalculate();
});
});