【问题标题】:Is there a way to resize grid boxes?有没有办法调整网格框的大小?
【发布时间】:2021-12-27 08:06:26
【问题描述】:

我有一个 react 应用程序,我在其中创建了大约一百万个网格框,所有框都应该适合即时屏幕(我希望每个框都很小)。我正在使用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 个盒子,它看起来像这样

有人能指出正确的方向吗?

【问题讨论】:

    标签: javascript css reactjs flexbox css-grid


    【解决方案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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 2013-01-24
      • 2021-08-30
      • 2021-03-14
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多