CSS grid can do it. Resize the div to see the result:
div {
padding: 20px;
width: 200px;
border: 1px solid;
overflow: hidden;
resize: horizontal;
}
ul {
list-style: none;
padding: 0;
margin: 0;
display: grid;
grid-template-columns: repeat(auto-fit, 40px); /* width of elements here */
grid-auto-rows: 40px; /* height here */
grid-gap: 4px;
justify-content: center; /* this will do the magic */
}
ul li {
background-color: wheat;
}
<div>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>