Compare the same layout using FlexBox and Grid layout system in CSS
FlexBox for just display items
Practically FlexBox is great to just display items along each other regardless of having the same size for al items. We can display items perfectly fine in the layout:
As an example with using flex: 1 1 auto; or just flex: auto; we give items the whole space they can get based on their content.
Grid layout to have horizontal and vertical alignment
Generally with grid we could have alignment in both directions as grid is a two dimensional system. But FlexBox is one dimensional basis. We could perfectly align a layout in grid like below:
As we explained in this article about using minmax() and auto-fit here we also use that t create columns:
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
Therefor each column will be at least 150px wide and the rest of the columns in the row will divide the space using one fraction of unit.
Same layout in FlexBox
Alternatively we could build the same layout in FlexBox:
See the Pen Smashing Flexbox Series 4: wrapped flex items flex-basis 150px; by rachelandrew (@rachelandrew) on CodePen.
So in here we have we have two lines of code to make it happen. We use flex: 1 1 150px; to calculate the column width for items and we gave the container flex-wrap: wrap; to wrap items into multiple lines.
Clearly with grid we align items perfectly and in FlexBox we use all the space given which takes us to where it is really good at over grid:
FlexBox over Grid
Technically if we need items to wrap in a few lines but also take as much space as needed in a line basis layout FlexBox is the perfect choice. Take a look at the same layout with different usage:
Ideally this is great for tag management and category based links for example. We just added this line to the container to make it centre:
We didn’t need a strict layout for this case. Also as we can see FlexBox is the perfect choice to centre items so far:
To wrap up this is from Rachel Andrew to explain both FlexBox and Grid:
The grid example is of two-dimensional layout. Layout in rows and columns at the same time. The Flexbox example is one-dimensional layout. We have wrapped flex lines but space distribution is happening on a line by line basis. Each line is essentially acting as a new flex container in the flex-direction.
Thank you for reading.