It sounds very much like you want to use the CSS attribute: Flexbox
With a flexible frame, you can define the maximum and minimum width and height, and the maximum / maximum number of elements before they hit a new line.
The beauty is that you let the browser calculate the width, you just define max, min, margin and padding.
And its all CSS, no javascript required
Take a look at the examples in css tricks and play with it. This link is relatively old, so some of the vendor prefixes are no longer needed.
Hope this helps!
EDIT: More info on flex attribute can be found in Mozilla
source share