What CSS grid can do that flex cannot?

Recently I had a problem where I had to make a responsive UI. On mobile, it has one column and on desktop two. Sounds simple initially, and it did to me as well.

Mobile

Desktop

My initial thought was just to use flex with 2 columns. However, there is a catch. The blocks on the right have to be in between the blocks on the left on mobile. This makes things very complicated with flex if not impossible. We also don't want to duplicate components and just show/hide them based on screen size.

Luckily, my colleague showed that we can utilize css grid here. In particular grid areas. Here is the result we want.

As you can see after reducing the size, the blocks on the right jump in-between main and main-below blocks. If you're on mobile now tailwind playground will only show the mobile version 🙂

So, the solution is to split your grid parts into areas you want to control, give them a name, and then place them in any way you want using grid-template-areas. On bigger screens just position the areas in a different way.

.demo-grid {
  grid-template-areas:
    "main"
    "sidebar"
    "main-below";
}

.area-main {
  grid-area: main;
}

.area-main-below {
  grid-area: main-below;
}

.area-sidebar {
  grid-area: sidebar;
}

@screen sm {
  .demo-grid {
    grid-template-columns: 1fr 30%;
    grid-template-rows: auto 1fr;
    grid-template-areas:
      "main       sidebar"
      "main-below sidebar";
  }
}

When I heard the grid idea first I was skeptical that it will still look like a grid. In particular, the main-below area will be rendered below the sidebar on bigger screens. That is actually what happens. However, we can solve that using

grid-template-rows: auto 1fr;

To learn more about css grids I advise watching Laracasts CSS Grids for Everyone. Or just search tailwind grid on youtube. There are plenty of good resources 🙂

Comments (1)

Edidiong Asikpo's photo

Just like you, I always jump into using Flexbox first before switching to Grid (when I realize I couldn't achieve what I wanted.)

Insightful tip Ernestas Kvedaras. Going forward, I'd think more about the implication of using a flexbox or grid before jumping into writing the code. 😃