JSFiddle - React, Tailwind, and code Playground
HTML
<ul id="parent">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li class="dummy"></li>
</ul>
CSS
ul {
display: flex;
display: -webkit-flex;
flex-direction: row;
-webkit-flex-direction: row;
flex-wrap: wrap;
-webkit-flex-wrap: wrap;
justify-content: center;
-webkit-justify-content: center;
margin: 0;
padding: 0;
}
li {
list-style-type: none;
border: 1px solid gray;
margin: 15px;
padding: 5px;
width: 200px;
}
.dummy {
visibility: hidden;
}
JavaScript
const handleResize = () => {
const item_box = document.getElementById('parent')
const list_length = item_box.clientWidth
const product_card_length = 200 + 30 + 30 // length of your child element (30, for margin & padding left & right each)
const item_in_a_row = Math.round(list_length/product_card_length)
const to_be_added = item_in_a_row - parseInt(6 % item_in_a_row) // listObject is the total number items
const left_to_set = (to_be_added - 1 ) * product_card_length // -1 : dummy item has width set, so exclude it when calculating the left margin
const dummy_product = document.querySelectorAll('.dummy')[0]
dummy_product.style.marginLeft = `${left_to_set}px`
}
handleResize() // Call it first time component mount
window.addEventListener("resize", handleResize);