Flexbox is better than floating or tables for dynamic rows of items

1 year 4 months ago

Here is another bit of code I find myself looking up recently. Flexbox is my new favorite layout tool.  It lets you set even boxes in a row with perfect space between the element and not on the outside.  It is surprisingly easy to use and gives you a perfect way to lay out dynamic content.  Here is the base code to use on the container:

.container{
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
}

Then just set a width for the items in the row.  For this example I am going to use a 4 column row, so I will set them all to 23%.

The only weird part about this is when you have the last row with an uneven amount of items.  They will be set far apart from each other and not in the row as you would expect with the same spacing as the above items.

To fix this issue I have been adding a blank item at the end of the list and styling it like so.

.empty{
    display:none;
}

.container .views-row:nth-child(2n+1).empty{
    width:48.66%;
    display:block;
}

.container .views-row:nth-child(2n+0).empty{
    width:74.29%;
    display:block;
}

.container .views-row:nth-child(4n+0).empty{
    width:23%;
    display:block;
}

.container .views-row:nth-child(4n+1).empty{
    display:none;    
}

The basic idea is to stretch the last item in the row to the correct dimensions.  Perhaps someday there will be a fix for this, but for now I feel like it is worth it to add this code and use flexbox instead of doing some crazy floating or inline block design.

< Return to Code Listing