Why does a horizontal scrollbar appear in portrait mobile view with CSS Grid layout but not flexbox?

Hello,
I have a code block with long text, and a horizontal scrollbar appears in mobile view, which I don’t want.

I have this CSS that handles the code block, and it works as expected with a flexbox layout, overflow: auto takes effect, and no scrollbar appears.

pre {
  padding: .8em;
  overflow: auto;
  border-radius: 0.3125em;
  background-color: #E8E8E8 !important;

  &::-webkit-scrollbar {
    width: 10px;
    height: 10px;
    background-color: transparent;
  }

  &::-webkit-scrollbar-track {
    border-radius: 10px;
    background-color: transparent;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: #bbbbbb;
  }
}

Here’s the full code, but you need to reduce the size of the winow to get the mobile view:

I have the same layout using only flexbox without any grid, and I don’t have this problem. The issue only occurs when I’m using grid.

I managed to fix the problem by using overflow: auto on the main element. As I said, this problem is grid related, the reason I needed that on the main which is a grid area. If I disable grid, things just work fine, the overflow: auto is enough on just the pre element.

However, I’m not sure if applying the overflow to main is the proper solution because I just added the css declaration by trial and error without any thinking. And since this overflow: auto is now defined on the main I’m wondering if it won’t mess with other stuff later on.

I can also fix the problem by applying grid-template-columns: minmax(0, 1fr); like so:

.grid-container {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: minmax(0, 1fr);
  grid-template-areas:
    "header"
    "main";
}

This doesn’t require overflow: auto on the main element. I’m not sure which solution is better.

That’s because of how flex and grid work.

Flex is unidirectional (row OR column) where grid is bi-directional (row AND column). As such, with flex the sizing of one container doesn’t affect the sizing of another container. With grid, the sizing is based on the largest container, and all containers are made the same size.

In this use case (single column), there is no real benefit to using grid. Flex would work just fine. Though I’d even argue that neither are necessary and using the default display:block behavior will work just fine as well.

1 Like

Due to the way grid works you need to specify the min-width otherwise it fits content as that’s the default for grid I believe.

e.g. add min-width:0 to that codepen and your pre will get scrollbars as required.

main {
  grid-area: main;
  padding: 0 1em;
  min-width:0;
}

More info here:

You’re right. For the purposes of this demo, a grid is not necessary, but the overall layout of the website does utilize a grid system. What I’ve shown here is more of a snippet, and I need to adhere to the grid layout in the final design.