Search code examples
csscss-grid

How do I prevent a CSS grid blowout when using gap?


Consider this simple layout:

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
</div>
.container{
  display: grid;
  grid-template-columns: repeat(100, minmax(0, 1fr));
  gap: 0;
  max-width: 100px;
}

.box {
  height: 100px;
  min-width: 0px;
  grid-column: span 30;
}

The result is what you'd expect. Two 30px wide children inside a 100px wide container.

Working grid layout

If you then change gap: 0; to gap: 2px;, the layout does something unexpected. The grid children grow much wider than they should, and blow out of the container element.

enter image description here

A strange detail is that gap:1px; also works fine. Only gaps > 1px cause the issue.

Here's a demo:

.container {
  display: grid;
  grid-template-columns: repeat(100, minmax(0, 1fr));
  gap: 0;
  max-width: 100px;
  margin-bottom: 20px;
  padding: 5px;
  background-color: LightGrey;
}

.container1 {
  gap: 0px;
}

.container2 {
  gap: 1px;
}

.container3 {
  gap: 2px;
}

.box {
  height: 100px;
  min-width: 0px;
  grid-column: span 30;
}

.box1 {
  background-color: DarkBlue;
}

.box2 {
  background-color: CornflowerBlue;
}
No gap, no problems
<div class="container container1">
  <div class="box box1"></div>
  <div class="box box2"></div>
</div>

1px gap, still good
<div class="container container2">
  <div class="box box1"></div>
  <div class="box box2"></div>
</div>

2px gap, ?!?!
<div class="container container3">
  <div class="box box1"></div>
  <div class="box box2"></div>
</div>

Does anyone have an explanation for this strange behavior, and even better, a way to prevent it? Thanks!

Edit: Thanks to @Jhecht, I've found a good solution. Posted as an answer below.


Solution

  • Thanks to the comment from @Jhecht I've figured out a good answer for my case.

    The issue here is that a 2px gap * 100 columns = 200px, which is greater than the max-width of the container. I need a flexible solution that deals with arbitrary container widths and gap sizes, given a 100 column grid.

    The answer is this nice little bit of modern CSS: gap: min(2px, 1%);

    If the container is wide enough, the pixel value will be applied. Otherwise a 1% gap will be applied, which is the maximum size a gap can be given 100 columns.

    Here's a working demo:

    .container {
      display: grid;
      grid-template-columns: repeat(100, minmax(0, 1fr));
      gap: min(2px, 1%);
      max-width: 100px;
      margin-bottom: 20px;
      padding: 5px;
      background-color: LightGrey;
    }
    
    .box {
      height: 100px;
      min-width: 0px;
      grid-column: span 30;
    }
    
    .box1 {
      background-color: DarkBlue;
    }
    
    .box2 {
      background-color: CornflowerBlue;
    }
    <div class="container">
      <div class="box box1"></div>
      <div class="box box2"></div>
    </div>