How to choose between grid and flex for a listing page

How to choose between grid and flex for a listing page

Stavros Ioannidis's photo
Stavros Ioannidis
·Jul 22, 2022·

2 min read

When we need to show a list of items, such as products in a product list page, we have the following two css alternatives:

  • display: grid
  • display: flex

I will demonstrate both here and I will explain why I choose one over the other.

Usually, we have a container around our content that limits its width to a maximum to keep it readable on large screens. In the demonstrations below I will use a container with a max-width of 400px and an Item width of 100px with a 10px gap between items. This means each row will fit 3 items (3x100px + 2x10px = 320px), and 80px will remain empty. We also need the items to be centered within the container.

Using flex

When using flex to create a grid-like structure we have to use flex-wrap. We make sure that the dimensions of our items are ok using flex-shink and flex-grow if needed. We need items to be centered so we will use justify-content: center. Here is a demo:

ul {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 10px;

We can see a problem here. The last row is not complete and the items are centered within this row. This doesn’t look like items in a grid. If we change to justify-content: flex-start everything will be on the left side, and all the available free space will be on the right. Not pretty.

Using grid

By using grid we don’t need to define something like flex-wrap but we need to define the columns' widths. In our example, we know that each item needs to be 100px wide, and the number of columns should vary depending on the width of the container. To achieve this we will use the repeat function with the auto-fill value. To center the items in the container we will use again justify-content: center.

Here is the demo:

ul {
    display: grid;
    grid-template-columns: repeat(auto-fill, 100px);
    justify-content: center;
    gap: 10px;

The difference here is that although we used justify-content: center the last row is left aligned and the items are kept within the grid lines. This is much better than flex for this case.

A grid with justify-content: center centers the whole grid, while a flex container with justify-content: center centers the individual items.


With our demonstrations here we showed that when you’re making a listing page it’s better to use display: grid rather than display: flex. Flex has its advantages in different use cases.

If you enjoyed this post, please share.

Did you find this article valuable?

Support Stavros Ioannidis by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
Share this