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)
5 Replies
Grid can do what you want. You will need to use
grid-auto-flow to change how the item are filled in to get your first point: https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/grid-auto-flowMDN Web Docs
grid-auto-flow - CSS | MDN
The grid-auto-flow CSS property controls how the auto-placement algorithm works, specifying exactly how auto-placed items get flowed into the grid.
The last point will almost certainly not hold if the button's text content is very long (longer than the viewport is wide) but you can't do much about that if you don't want text wrapping at all
Yes, I can ignore the possibility that a button would be larger than the container.
I already tried that one, it didn't work.
what I currently have is flex, with wrap enabled, with flex:1 so that all buttons on the same line are the same size, and an override on the min-width of the buttons so that I can influence on a case-by-case basis the number of buttons per row (and try and ensure that it's the same for every row).
Do you have a codepen of it? Cause it should work
Grid auto-fit isn't supported for column sizes dependent on content size. So unfortunately, you have to either set the column min-size to a hard-coded value, hard-code the number of columns per row, or use a flex display and have the wrapped elements stretched to fill the row.