首页 > 解决方案 > 具有纵横比单元格以填充高度的 CSS 网格

问题描述

我想创建一个具有固定大小(28x20)网格的 CSS 网格,该网格填充所有可用高度,同时保持单元格具有相同的纵横比(1/1)。

请参见下面的简化示例。理想情况下,这个 3x3 网格将填充高度并在右侧有空白空间,但它会填充宽度并创建一个垂直滚动条。

这只适用于最新版本的铬(电子应用程序)

建议?

.ctnr {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 1px;
  height: 100%;
  overflow:hidden;
}


.cell {
  background: orange;
  aspect-ratio:1;
}

body {
  height: 100%;
  width: 100%;
  margin: 0;
  box-sizing: border-box;
}
<div class="ctnr">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>

标签: htmlcsscss-gridaspect-ratio

解决方案


我尝试了一些想法。我的解决方案可能并不完美,但也许会对您有所帮助。您可以vh在您的网格中使用作为调整大小的基础。因此,如果我们需要每列 3 个方格,我们可以33vh为列和行设置。还要添加grid-auto-flow: column;以使其面向列。

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  height: 100vh;
  display: grid;
  gap: 1px;
  /* Maybe use something like calc(100vh / 3 - 1px) for more precise calculation */
  grid-template-columns: repeat(auto-fill, 33vh);
  grid-template-rows: repeat(auto-fill, 33vh);
  grid-auto-flow: column;
}

.cell {
  background-color: #121212;
}
<div class="container">
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
</div>


推荐阅读