如何自动调整网格项目的大小以适合父高

时间:2019-11-14 04:40:48

标签: css css-grid

我有5个元素,它们按如下网格布局划分为两列:

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>

如何调整2、4个元素的大小以适合屏幕的高度,例如2和4的高度等于1.5、1,3和5的高度?

1 个答案:

答案 0 :(得分:0)

我将使用grid-template-areas将其分解为另一对网格,以对齐新容器,以便您拥有左右网格。如果要保持顺序,则将item2item4分隔到各自的容器中。

.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>