To use CSS Grid or To use CSS Flexbox? That is the question

Using the CSS position property to locate elements on a webpage can be very tricky. This is where CSS Flexbox and CSS Grid comes in handy. What are they? What are the differences? And finally, which one should I use? Here is a simple breakdown of both.

CSS Flexbox

CSS Flexbox is also called CSS Flexible Box Layout Module. It is 1-dimentional so elements can line up in one direction, horizontal or vertical.

The main-axis is either a row(horizontal) or column(vertical) direction with cross-axis in perpendicular direction from main-axis. When calculating, it calculates one line at a time and has no regards for the other rows or columns. If elements are lining up in horizontal direction, it does not line up in a vertical direction.

The best part is that the Flex container can allocate the available space by using its children containers (flex items) to stretch to fill the empty space, or shrink to prevent an overlap. Using CSS Flexbox is a great way to design flexible and responsive layout for a webpage as it focuses on content flow.

A few basic terminologies:

flex container is a parent container that contains its children container, flex item.

Some of the properties when using CSS Flexbox:

CSS Flexbox vs CSS Grid

CSS Grid

CSS Grid is also called CSS Grid Layout Module. CSS grid provides 2-dimensional layout, columns and rows which are great for dividing a webpage into blocks and use properties to size, position and layer them.

It can align the elements in both directions. Precise content placement and accurately controlling the position is CSS grid’s strong suit. When calculating its position, CSS thinks in both directions.

Grid does not have to be used in the entire webpage. It can be used only as part of a page. It can also be used in conjunction with CSS Flexbox. Grid allows layering like overlapping the text to an image.

A few basic terminologies:

Grid container is a parent element and it can have one or more grid items, its children.

Some of the properties when using CSS Grid:


Another thing to keep in mind as a frontend developer when using CSS Grid and CSS Flexbox is the browser compatibility. Below image shows a list of browsers that support CSS Grid and CSS Flexbox.

Legend for below two images:

Green = supported

Red = not supported

Olive = partial support

Browsers that supports CSS grid:

Browsers that supports CSS flexbox

If you want to learn grid and flexbox by practice, these games offer a simple and fun hands on experience. I highly recommend Flexbox Froggy.

Games to learn CSS

Here are few of many resources if you want to dive deeper into these two topics.

w3schools CSS Grid

w3Schools CSS Flexbox

Mozilla CSS Grid Layout

Mozilla CSS Flexible Box Layout