I have a container that I want to fit a number of children in horizontally, but I know I have more children than will often fit.
+-----------------------+
| |
| |
+-----------------------+
+----+ +----+ +----+ +----+ +----+ +----+
| | | | | | | | | | | |
| | | | | | | | | | | |
+----+ +----+ +----+ +----+ +----+ +----+
Using only CSS, how do I only display the items that can fit, and expand them to fit snugly?
Desired result:
+-----+-----+-----+-----+
| | | | |
| | | | |
+-----+-----+-----+-----+
@NathanArthur's solution is great for cases where you have a fixed height, however in the case you don't know your height things get a bit more hairy.
To do this without a fixed height you can use
display: grid
. Browser support for css grid currently is pretty limited to latest versions, but I believe this would be one of few (if not the only) way to do with without a fixed height.But what you can do is set up a
display: grid
withauto-fit
columns using therepeat()
function combined with theminmax()
function. This will give you columns with a minimum size set by you, which will fill the rest of the space needed. Combine this withgrid-auto-rows: 0px
which will hide any additional rows added by child auto placement which happens if they start to go outside the bounds of the definedgrid-template
parameters. Looks a little something like this, note no defined heights and variable widths:The solution can be broken into two pieces:
Hiding elements that don't fit
overflow: hidden;
so children that wrap disappear.(Thanks to this answer for inspiring this part of the solution.)
Expanding children that do fit to take up available space snugly
display: flex;
so children can grow.flex-wrap: wrap;
so children that won't fit can still wrap and disappear.flex: 1 0 [desired minimum width];
so children can only grow, not shrink.The result