I encountered a similar issue and shared my solution in this post:
How can I make a container div the same width as its floating children and center it when there are multiple rows of floating children?
In my scenario, I had a structure like this:
<div class="centered">
<div class="container">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
</div>
Upon analysis, jQuery seemed to offer a viable solution. By dynamically adjusting the width of the containing div based on window size and child elements, we were able to achieve the desired outcome.
For implementation details, refer to this fiddle:
var resizeContainerDiv = function() {
var screenWidth = $(window).width();
var childWidth = $(".child").outerWidth();
var innerContainerWidth = Math.floor(screenWidth / childWidth) * childWidth;
$('.container').css('width', innerContainerWidth);
}
$(window).on("load", resizeContainerDiv);
$(window).on("resize", resizeContainerDiv).resize();
.centered {
text-align: center;
}
.container {
background: red;
padding: 10px;
display: inline-block;
}
.child {
width: 100px;
height: 100px;
float: left;
}
.child:nth-child(even) {
background: green;
}
.child:nth-child(odd) {
background: blue;
}
<div class="centered">
<div class="container">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
</div>
https://jsfiddle.net/02arvnLx/1/