Search code examples
csscss-grid

CSS grid - have one row not contribute to width of column, resulting in wrap


I want every "cell" in my grid to contribute to the column widths, except for a particular one - I want it to expand its height to contain (forcing a word wrap). Is there a way to do this?

body{
  display:flex;
}

.grid-container{
 display: grid;
 gap: 20px;
 grid-template-columns: auto auto auto;
 .see-all{
   display: grid;
   grid-column-start:1;
   grid-column-end:4;
   grid-template-columns:subgrid;
   :nth-child(1){
     column:1;
   }
   :nth-child(2){
     column:2;
   }
   :nth-child(3){
     column:3;
   }
  }
  .other{
    grid-column: 1 / span 3;
  }
}
<body>
  <div class="grid-container">
   <div class="see-all">
      <div>Apple</div>
      <div>Banana</div>
      <div>Coconut</div>
    </div>
    <div class="see-all">
      <div>Date</div>
      <div>Eggplant</div>
      <div>Fig</div>
    </div>
    <div class="other">
This row is just too long, I was this to use the width of the column (set by other elements) to then cause this to word wrap.
    </div>
  </div>
<body>


Solution

  • The min-width:100%; width:0 trick will do in your case. The grid track sizes are calculated based on its width, then its size will be grown back based on the size of the track because of min-width.

    body {
      display: flex;
    }
    
    .grid-container {
      display: grid;
      gap: 20px;
      grid-template-columns: auto auto auto;
      .see-all {
        display: grid;
        grid-column-start: 1;
        grid-column-end: 4;
        grid-template-columns: subgrid;
         :nth-child(1) {
          column: 1;
        }
         :nth-child(2) {
          column: 2;
        }
         :nth-child(3) {
          column: 3;
        }
      }
      .other {
        grid-column: 1 / span 3;
      }
      .long-cell {
        min-width: 100%;
        width: 0;
      }
    }
    <body>
      <div class="grid-container">
        <div class="see-all">
          <div>Apple</div>
          <div>Banana</div>
          <div>Coconut</div>
        </div>
        <div class="see-all">
          <div>Date</div>
          <div>Eggplant</div>
          <div>Fig</div>
        </div>
        <div class="other long-cell">
          This row is just too long, I want to force the elements in this row to word wrap and not contribute to the grid
        </div>
      </div>
    
      <body>