CSS Grid (vs) Flexbox

Benji
3 min readSep 13, 2021

--

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

CSS Grid focuses on 2d layouts (rows AND columns).

Flexbox

Flexbox is designed for 1d layouts (either rows OR columns).

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.

Styling inspiration from here. Avatar generated by this awesome generic online avatar generator.

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.

Checkout my JSFiddle: https://jsfiddle.net/benjib/hk1L67qe/84/

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.

Checkout my JSFiddle: https://jsfiddle.net/benjib/vpyarnh7/238/

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.

add a parent element — like “.cards”
This is your snippet to create your responsive auto grid.
You can also try it on your own with my JSFiddle: Here is my JSFiddle: https://jsfiddle.net/benjib/wedbvsfk/8/

--

--

Benji

Software & Mobile — Engineer | interested in best practices and always looking for new challenges