Search code examples
htmlcssflexbox

Dynamically sizing flex items while keeping consistent size on last row


My flexbox container has a variable width and children can shrink until 150px and grow up to 250px. This works as intended except, when the last row is not full of children, they grow larger than children on full rows. How can I have varying sizes for flex children while keeping all children the same size?

#products-list {
    position:relative;
    display: flex;
    flex-flow: row wrap;
    width:100%;
}

#products-list .product {
    min-width:150px;
    max-width:250px;
    margin:10px 10px 20px 10px;
    flex:1;
}

I created a dynamic situation in jsFiddle


Solution

  • Unfortunately, in the current iteration of flexbox (Level 1), there is no clean way to solve the last-row alignment problem. It's a common problem.

    It would be useful to have a flex property along the lines of:

    • last-row
    • last-column
    • only-child-in-a-row
    • alone-in-a-column

    This problem does appear to be a high priority for Flexbox Level 2:

    Although this behavior is difficult to achieve in flexbox, it's simple and easy in CSS Grid Layout:

    In case Grid is not an option, here's a list of similar questions containing various flexbox hacks: