Auto-optimized grid columns and rows

I have a container with buttons inside it. The buttons' text contents is of different sizes, always non-empty and inferior to the width of the container, and there is an arbitrary number of buttons. That means I can't hardcode any width value.
I want
- that the buttons are filled from left to right, but wrap in another line/row if it overflows,
- that each button has the same width as every other one, even those on other lines,
- that no button becomes shorter than the size required by its content

I tried display:flex and display:grid but didn't manage to have all those to work (flex breaks the second rule and grid breaks the first or the third, or requires a hardcoded value)
Was this page helpful?