Search code examples
csscss-grid

CSS Grid wrapper does not expand to size of items


I have an element with display: grid;. The parent of the grid has a max-size and will allow the grid to be scrolled if needed.

The issue is that the grid element does not expand to the size of its children. If you scroll right you can see that the color of .grid (red) ends and .b (blue) keeps going. I'm probably missing a property I don't know about?

.wrapper {
  max-width: 200px;
  overflow: auto;
}

.grid {
  max-width: none;
  display: grid;
  grid-template-columns: 150px 150px;
  background: red;
  border-bottom: 3px solid red;
}

.a {
  background: rgba(0, 255, 0, 0.5);
  border-bottom: 3px solid green;
}

.b {
  background: rgba(0, 0, 255, 0.5);
  border-bottom: 3px solid blue;
}
<div class="wrapper">
    <div class="grid">
        <div class="a">a</div>
        <div class="b">b</div>
    </div>
</div>


Solution

  • You can try inline-grid option in display property. When you use inline-grid then all direct children of the grid container automatically become grid items.

    
    .grid {
      max-width: none;
      display: inline-grid;
      grid-template-columns: 150px 150px;
      background: red;
      border-bottom: 3px solid red;
    }
    

    https://jsfiddle.net/aviboy2006/vLd850os/

    Reference : https://www.w3schools.com/css/css_grid.asp