网格卡采用最高元素的高度

问题描述 投票:0回答:1

我有几张卡片在网格中渲染,最大数量为: 4 列 x 行,卡片的高度是可变的,具体取决于卡片内的内容。

有没有一种简单的方法可以确保所有卡片的高度与最高高度的卡片相同?

现在,我的第一行中的所有卡片都完美适应,因为那是我最高的卡片所在的位置。但是我的第二行没有达到所需的高度。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Grid</title>
  <style>
    .App {
      font-family: sans-serif;
      text-align: center;
      box-sizing: border-box;
    }

    * {
      box-sizing: border-box;
    }

    .container {
      display: grid;
      gap: 15px;
    }

    .row {
      display: grid;
      grid-template-columns: repeat(4, minmax(0, 1fr));
      gap: 15px;
    }

    .item {
      background-color: rgb(126, 136, 145);
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="item">
        <p>
          This element can have a variable height based on the content placed
          on it
        </p>
      </div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
    </div>

    <div class="row">
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
    </div>
  </div>
</body>
</html>

javascript css reactjs
1个回答
0
投票

你可以使用JS将你的高度固定为最大高度:

// Get items
var items = document.querySelectorAll('.item');
var maxHeight = 0;

// Loop all items and check height, if bigger than max then save it
items.forEach(function(item) {
  var itemHeight = item.offsetHeight;
  if (maxHeight < itemHeight) {
    maxHeight = itemHeight;
  }
});

// Set ALL items to this height
items.forEach(function(item) {
  item.style.height = maxHeight + 'px';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Grid</title>
  <style>
    .App {
      font-family: sans-serif;
      text-align: center;
      box-sizing: border-box;
    }

    * {
      box-sizing: border-box;
    }

    .container {
      display: grid;
      gap: 15px;
    }

    .row {
      display: grid;
      grid-template-columns: repeat(4, minmax(0, 1fr));
      gap: 15px;
    }

    .item {
      background-color: rgb(126, 136, 145);
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="item">
        <p>
          This element can have a variable height based on the content placed
          on it
        </p>
      </div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
    </div>

    <div class="row">
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
    </div>
  </div>
</body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.