Search code examples
csscss-grid

How can I make CSS grid left column fit the number of rows


I'm dynamically creating a grid layout. My goal is to have the column on the left always be the same as the height of the rows. I've gotten it to work for 2+ rows, but it breaks if there is only a single row.

Here's my CSS:

.grid {
    display: grid;
    grid-template-columns: 3rem 1fr;
    grid-template-rows: 1fr 1fr;
    width: 200px;
    min-height: 3rem;
    background-color: grey;
}

.left-side {
    background-color: blue;
    grid-column: 1 / 1;
    grid-row: 1 / span 1000;
}

.row {
    background-color: lightblue;
    border: solid red 1px;
}
<div class="grid">
    <div class="left-side"></div>
    <div class="row">Bad!</div>
</div>

<br>

<div class="grid">
    <div class="left-side"></div>
    <div class="row">Good!</div>
    <div class="row">Good!</div>
</div>

<br>

<div class="grid">
    <div class="left-side"></div>
    <div class="row">Good!</div>
    <div class="row">Good!</div>
    <div class="row">Good!</div>
</div>


Solution

  • Just add grid-row: span 2 to .row

    .grid {
      display: grid;
      grid-template-columns: 3rem 1fr;
      grid-template-rows: 1fr 1fr;
      width: 200px;
      min-height: 3rem;
      background-color: grey;
    }
    
    .left-side {
      background-color: blue;
      grid-column: 1 / 1;
      grid-row: 1 / span 1000;
    }
    
    .row {
      background-color: lightblue;
      border: solid red 1px;
      grid-row: span 2;
    }
    
    /* fix for a small bug. you can see by removing */
    .row:nth-last-of-type(n+2) {
      grid-row: unset;
    }
    <div class="grid">
      <div class="left-side"></div>
      <div class="row">Good!</div>
    </div>
    
    <br>
    
    <div class="grid">
      <div class="left-side"></div>
      <div class="row">Good!</div>
      <div class="row">Good!</div>
    </div>
    
    <br>
    
    <div class="grid">
      <div class="left-side"></div>
      <div class="row">Good!</div>
      <div class="row">Good!</div>
      <div class="row">Good!</div>
    </div>
    
    <br>
    
    <div class="grid">
      <div class="left-side"></div>
      <div class="row">Good!</div>
      <div class="row">Good!</div>
      <div class="row">Good!</div>
      <div class="row">Good!</div>
      <div class="row">Good!</div>
      <div class="row">Good!</div>
      <div class="row">Good!</div>
    </div>