Read more

How to prevent a 1fr grid column overflow

Dominic Beger
August 28, 2023Software engineer at makandra GmbH

TL;DR:

Grid elements have min-width: auto in a 1fr column, which may lead to overflows. With minmax(0, $width) you can reset the min-width.


Say you have a simple grid layout:

.container
  .first-item
  .second-item
  .third-item
.container
  display: grid
  grid-template-columns: 100px 1fr 100px
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Your expectation is now that

  • the first item will be located on the left hand side with a fixed width of 100px
  • the third item will be located on the right hand side, also with a width of 100px
  • the second item will fill up the remaining space in the center.

That's correct as the grid layout will try to do that:

+---------+----------------------------+---------+
|  <div>  |  <p> - 10 characters long  |  <div>  |
+---------+----------------------------+---------+

However, if .second-item's content is too large to fit into the reserved space, it will cause an overflow, effectively overlapping the entire space on the right hand side and .third-item won't be visible anymore. Grid will not shrink it for you, even if .second-item could be rendered smaller without problems or has because you defined behavior for it.

+---------+--------------------------------------+
|  <div>  |  <p> - 1000 characters looooooooooooong |  <div>  |
+---------+--------------------------------------+

Try it on CodePen Show archive.org snapshot .


There are two ways to fix this:

The overflow property

Of course, you may just set overflow: hidden or maybe on .second-item and/or add some overflow behavior and you're done. In some cases, this might not be the solution because the content should be shrinked properly instead of just killing the overflow.

Using minmax(0, 1fr)

You can use minmax(0, 1fr) instead of 1fr to achieve the correct layout:

.container
  display: grid
  grid-template-columns: 100px minmax(0, 1fr) 100px

1fr resolves to minmax(auto, 1fr) which means that your item must not shrink below its content-size because its minimum width is auto. If the content is now larger than the visible space, it will just overflow it and the grid can't do anything about it for you.

By changing it to minmax(0, 1fr), you will allow the container to shrink down until it eventually reaches 0px. The grid will then automatically determine the necessary width to split and fill the space properly.


Confer CSS: Flex and "min-width".

Dominic Beger
August 28, 2023Software engineer at makandra GmbH
Posted by Dominic Beger to makandra dev (2023-08-28 11:33)