Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I allow flex-items to grow while keeping the same size?

Tags:

css

flexbox

Flexbox is one of the coolest tools a web designer could wish for. Unfortunately, sometimes it's not immediately obvious what I'm supposed to do. Take, for example, this plunk. I'd like for the items to expand to fill the row, without expanding all the way across in the last row.
My CSS contains this important stuff:

.recipe-picker recipe {
    -webkit-flex: 0 1 8em;
    flex: 0 1 8em;
    
    height: 12em;
}

If I change the 0 to any positive number (which corresponds to the flex-grow property), the last item row will stretch in a super ugly way. The rest of the items behave rather nicely, but the last row should keep the same size as the rest of the items.
What can I do to fix this behavior?

like image 709
striking Avatar asked Jan 21 '15 18:01

striking


2 Answers

This is something that cannot be expressed via CSS Flexbox right now. Someone asked basically this exact question on the CSS Working Group Mailing List a few days ago, and the response was: "At the moment, no, this is not possible. This is a high-priority item for Flexbox 2, though.

You may be able to hack up something like you want using max-width, though -- that'll prevent flex items (particularly those on the last line) from growing indefinitely. Here's a forked version of your plunk with a nonzero flex-grow, and with max-width: 10em.

(I chose 10em arbitrarily; you could also use e.g. max-width: calc(100%/5), if you want to make sure each flex item takes up no more than 1/5 of the line, for example.)

like image 176
dholbert Avatar answered Nov 01 '22 09:11

dholbert


I achieved what you were looking for by adjusting flex-shrink.

.recipe-picker recipe {
flex: 0 0 8em;
}

I try to think of flex-grow and flex-shrink as "permission to expand". When either has a value, that means the element has permission to grow. When all elements have flex-grow, they will expand to the same size. But, the same rule holds true if they all have a flex-shrink value, too.

http://plnkr.co/edit/sxHUzIRPlbstpOzoGcR6?p=preview

like image 22
paceaux Avatar answered Nov 01 '22 10:11

paceaux