0

我有一个反应应用程序,我正在创建大约一百万个网格框,所有框都应该适合即时屏幕(我希望每个框都很小)。我正在使用 js 来计算每个盒子相对于盒子数量的高度和宽度。

var numOfBoxes = 1000 // this number can change anytime

var [height, width] = `${100/numberOfBoxes}%`

我使用在StackOverflow上找到的 CSS 创建了网格

#root {
  width: 100vw;
  height: 100vh
}
// I tried to use vh and vw to make the #root element fit the initial screen


.square-container {
  display: flex;
  height: 100%;
  width: 100%;
  flex-wrap: wrap;
}

.square {
  position: relative;
  flex-basis: calc(25% - 10px);
  margin: 5px;
  border: 1px solid;
  box-sizing: border-box;
}

.square::before {
  content: '';
  display: block;
  padding-top: 100%;
}

.square .content {
  position: absolute;
  top: 0; left: 0;
  height: 100%;
  width: 100%;
}

但是当我尝试增加或减少时,方块的大小保持不变numOfBoxes。我尝试从 DevTools 更改高度和宽度,但无济于事。

如果我渲染 100 个盒子或 1000 个盒子,它看起来像这样 网格

有人可以指出我正确的方向吗?

4

1 回答 1

1

您可以将 CSS 变量添加到根元素,将其用作网格类的一部分,然后使用setProperty.

// Using a setTimeout for this demo, but you would
// be adding this to your render method I expect
function changeWidth(width, count = 1) {
  document.documentElement.style.setProperty('--square-width', `${width}px`);
  if (count < 5) setTimeout(changeWidth, 2000, width +=5, ++count)
}

changeWidth(5);
:root {
  --square-width: 10px
}

.container {
  display: grid;
  grid-template-columns: repeat(3, var(--square-width));
  grid-gap: 5px;
}

.container div {
  background-color: red;
  aspect-ratio: 1;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

于 2021-11-16T08:37:42.697 回答