'Balance amount of elements per row according to the screen width and number of items

I followed this answer to get the product cards centered at the last row for an online store, it works perfectly.

I would like to know if it's possible to define a method to equate the number of articles based on the total amount, obtaining the maximum number of articles per row, responsive and centering the entire group.

For example 11 items = 4 + 4 + 3 for wide screens or 3 + 3 + 3 + 1 for narrow screens

This is what I have now:

enter image description here

This is what I would like to achieve:

enter image description here

I don't know the exact number of items each section will have, I'm looking for something generic for groups with even and odd content.

I know that a balance will not be possible for any quantity:

13 items = 5 + 5 + 3 / 4 + 4 + 4 + 1 / 3 + 3 + 3 + 3 + 2

I don't know if it's possible, any suggestions?

Trying to reason, if all the cards have the same width and margin, say 250px + 10px, maybe something can be done with measurements so that only items fit in each width.

For example:

3 items = row width = 790px

4 items = row width = 1030px



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source