How to auto resize grid items to fit parent height

I have 5 elements which were devided into two columns by grid layout like this:

Codepen

<!DOCTYPE html>
<html>
<head>
<style>
  .grid-container {
  display: grid;
  grid-template-columns: auto auto;
  grid-gap: 10px;
  background-color: #2196F3;
  padding: 10px;
}

.grid-container > div {
  background-color: rgba(255, 255, 255, 0.8);
  text-align: center;
  padding: 20px 0;
  font-size: 30px;
}
  </style>
</head>
<body>

<h1>The grid-row Property</h1>

<p>Use the <em>grid-row</em> property to specify where to place an item.</p>
<p>Item1 will start on row-line 1 and end on row-line 4:</p>

<div class="grid-container">
  <div class="item1">1</div>
  <div class="item2">2</div>
  <div class="item3">3</div>  
  <div class="item4">4</div>
  <div class="item5">5</div>
</div>
</body>
</html>

How can I resize for 2, 4 elements to fit the height of screen, such as the height of 2 and 4 will be equal to 1.5 the height of 1,3 and 5?

1 answer

  • answered 2019-11-14 05:40 F. Serna

    I would just break it down into another pair of grids using grid-template-areas to align the new containers so you have a left and right grid. If you want to keep the order the elements then separate item2 and item4 into their own container.

    .grid-container {
      display: grid;
      grid-template-columns: auto auto;  
      grid-gap: 10px;
      background-color: #2196F3;
      padding: 10px;
      grid-template-areas: 
        'left-container right-container'
    }
    
    .grid-container > div > div {
      background-color: rgba(255, 255, 255, 0.8);
      text-align: center;
      padding: 20px 0;
      font-size: 30px;
    }
    
    .left-container {
      display: grid;
      grid-row-gap: 10px;
    }
    
    .right-container {
      display: grid;
      grid-row-gap: 10px;
    }
    <div class="grid-container">
      <div class="left-container">
        <div class="item1">1</div>    
        <div class="item3">3</div>  
        <div class="item5">5</div>
      </div>
      <div class="right-container">
        <div class="item2">2</div>
        <div class="item4">4</div>    
      </div>  
    </div>