Search code examples
htmlcssstylescss-grid

How can I set the height of a row dynamically with grid?


I'm trying to build a grid where the first-row would have 400px and the second would be something like fit-content, since my first column is dynamically created and it can have an undertemined height.

The idea is, I have three blocks, 1 is dynamic, 2 and 3 are static, where 3 should always be below 2:

enter image description here

However I couldn't find a way to make the first row with a fixed value (400px) and the second auto to fit whatever height the block 1 have. If I set the first one auto and the second row 400px I get this:

.container {
  display: grid;
  grid-template-columns: auto auto;
  grid-template-rows: auto 400px;
  width: 400px;
}

.block-1 {
  height: 300px;
  width: 200px;
  background: red;
}

.block-2 {
  height: 100px;
  width: 150px;
  background: blue;
  grid-column: 3/5;
}

.block-3 {
  height: 100px;
  width: 150px;
  background: green;
  grid-column: 3/5;
  grid-row-start: 2;
}
<div class="container">
  <div class="block-1"></div>
  <div class="block-2"></div>
  <div class="block-3"></div>
</div>

Is there a way to do that with grid? I could change the structure of the grid, the way I bult is not a must.

P.S. Changing the HTML is not an option.


Solution

  • Is this what you want?

    .container {
      display: grid;
      grid-template-columns: auto auto;
      grid-template-rows: auto 400px;
      width: 400px;
    }
    
    .block-1 {
      height: 300px;
      width: 200px;
      background: red;
      grid-row: 1 / 3;
    }
    
    .block-2 {
      height: 100px;
      width: 150px;
      background: blue;
    }
    
    .block-3 {
      height: 100px;
      width: 150px;
      background: green;
      grid-column: 2/3;
      grid-row-start: 2;
    }
    <div class="container">
      <div class="block-1"></div>
      <div class="block-2"></div>
      <div class="block-3"></div>
    </div>