Before I started seriously researching “CSS Grid” I thought like:
“Oh a new css layout system. It has to be the new and better Flexbox — I can recommend to every frontend developer to use CSS Grid instead of Flexbox from now on”
But after a very short time I realized that it’s not “either or”, but rather that it makes sense to combine the two systems. This is also why I called this Story “CSS Grid (vs) Flexbox”. Let me explain the two systems and then give an example for a combination of the two systems.
Flexbox and CSS Grid are both CSS Layout Systems.
The main difference between Flexbox and CSS Grid is the dimmension.
CSS Grid
Flexbox
When to use Flexbox and when to use CSS Grid
This question is very easy to answer:
You should use CSS grid for layouts and Flexbox for alignments. You can (or should) use both together.
Example
Imagine you have to build something like this profile card.
Looking for grids and alignments
Grid
If we just focus on the grid for the whole component, we can define the grid like below.
The grid can be easily done with following CSS snippet by using grid-auto-flow.
The CSS Grid is now defined by 2 columns and 3 rows.
We use “grid-auto-flow” to automatically detect columns and rows. The image below shows the difference between “grid-auto-flow: column” and “grid-auto-flow: row”.
Alternatively, you could use “grid-template-areas” to define the grid.
Alignments (Flexbox)
Within the cells of the grid we can use Flexbox to align the inner elements (blue rectangles).
There is still so much to tell about CSS Grid
Please visit https://css-tricks.com/snippets/css/complete-guide-grid to get a complete guide of CSS Grid.
One last thing, I also found on this page, was the “Fluid Column Snippet”. With just a few lines of CSS you’ll get a responsive grid with no media-queries!
Imagine you’d like to have our user-card for a few users in a grid. The below snippet does this for you and also manages the container-width to display as many cards as possible in a row depending on the screen width.