skip to Main Content

I have a CSS grid whose elements are flex containers. I’m trying to make the grid’s columns auto-size based on the sizing rules of the flex items within the flex containers.

Below is an illustration of what I’m trying to achieve. Is it possible to obtain the desired behavior?

CodeSandbox

.grid {
  display: grid;
  grid-template-columns: max-content 1fr;
  grid-template-rows: 30px;
  border: 4px solid black;
}

.cell {
  display: flex;
  border: 4px solid orange;
  background: rgb(211, 211, 211);
}

.item {
  flex: 1 1 0;
  max-width: 200px;
  border: 4px solid blue;
}
<p><b>Desired behavior</b>: the flex item auto-grows up to its maximum width, which defines the size of the grid column</p>

<div class="grid" style="grid-template-columns: 216px 1fr;">
  <div class="cell"><div class="item"></div></div>
  <div class="cell"></div>
</div>

<p><b>Actual result</b>: the flex item doesn't auto-grow because the `flex` rule can't make its flex container grow</p>

<div class="grid">
  <div class="cell"><div class="item"></div></div>
  <div class="cell"></div>
</div>

2

Answers


  1. Add a min-width to the flex item that matches the max-width

    .grid {
      display: grid;
      grid-template-columns: max-content 1fr;
      grid-template-rows: 30px;
      border: 4px solid black;
    }
    
    .cell {
      display: flex;
      border: 4px solid orange;
      background: rgb(211, 211, 211);
    }
    
    .item {
      flex: 1 1 0;
      max-width: 200px;
      min-width: 200px;
      border: 4px solid blue;
    }
    <div class="grid">
      <div class="cell"><div class="item"></div></div>
      <div class="cell"></div>
    </div>
    Login or Signup to reply.
  2. Try setting the min-width of the flex container to the same value as the max-width property of the flex item.

    .cell{
      display: flex;
      border: 4px solid orange;
      background: rgb(211, 211, 211);
      min-width: 0; /* will allow cell container to shrink */
    }
    
    .item {
      flex: 1 1 0;
      max-width: 200px;
      border: 4px solid blue;
      /* set min-width to same value as max-width */
      min-width: 200px;
    }
    <p><b>Desired behavior</b>: the flex item auto-grows up to its maximum width, which defines the size of the grid column</p>
    
    <div class="grid" style="grid-template-columns: 216px 1fr;">
      <div class="cell"><div class="item"></div></div>
      <div class="cell"></div>
    </div>
    
    <p><b>Actual result</b>: the flex item doesn't auto-grow because the `flex` rule can't make its flex container grow</p>
    
    <div class="grid">
      <div class="cell"><div class="item"></div></div>
      <div class="cell"></div>
    </div>
    This should work
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search