How to prevent a 1fr grid column overflow

Updated . Posted . Visible to the public. Repeats.

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

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
Last edit
Dominic Beger
License
Source code in this card is licensed under the MIT License.
Posted by Dominic Beger to makandra dev (2023-08-28 09:33)